Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding a mask to an image using CSS
The CSS mask-image property allows you to create a layer over an element that can hide parts of it either partially or completely. This property is particularly useful for creating visual effects on images and text.
Syntax
selector {
mask-image: none | <image> | linear-gradient() | radial-gradient() | initial | inherit;
}
Possible Values
| Value | Description |
|---|---|
none |
No mask is applied (default) |
<image> |
Uses an image as the mask |
linear-gradient() |
Creates a linear gradient mask |
radial-gradient() |
Creates a circular gradient mask |
initial |
Sets the property to its default value |
inherit |
Inherits the value from parent element |
Example 1: Linear Gradient Mask
This example creates a fade effect using a linear gradient mask
<!DOCTYPE html>
<html>
<head>
<style>
.fade-mask {
width: 300px;
height: 200px;
background-image: url('https://www.tutorialspoint.com/static/images/simply-easy-learning.jpg');
background-size: cover;
background-position: center;
mask-image: linear-gradient(to top, transparent 0%, black 50%);
-webkit-mask-image: linear-gradient(to top, transparent 0%, black 50%);
}
</style>
</head>
<body>
<div class="fade-mask"></div>
</body>
</html>
An image with a gradient fade effect where the bottom portion gradually becomes transparent.
Example 2: Radial Gradient Mask
This example creates a circular mask effect
<!DOCTYPE html>
<html>
<head>
<style>
.circular-mask {
width: 300px;
height: 200px;
background-image: url('https://www.tutorialspoint.com/images/logo.png');
background-size: cover;
background-position: center;
mask-image: radial-gradient(circle, black 60%, transparent 70%);
-webkit-mask-image: radial-gradient(circle, black 60%, transparent 70%);
}
</style>
</head>
<body>
<div class="circular-mask"></div>
</body>
</html>
An image with a circular mask where the center is visible and edges fade to transparent.
Browser Support
The mask-image property has partial browser support. Most modern browsers require the -webkit- prefix for compatibility. Always include both the standard property and the prefixed version for better browser support.
Key Points
- Black areas in the mask make content visible
- Transparent areas in the mask hide content
- Gradients create smooth transitions between visible and hidden areas
- Always include the
-webkit-prefix for better browser compatibility
Conclusion
The mask-image property is a powerful tool for creating visual effects by selectively hiding parts of elements. Use gradients for smooth transitions and always include vendor prefixes for cross-browser compatibility.
