CSS masking
CSS masking allows you to create complex visual effects by selectively showing or hiding parts of an element based on a mask image or a mask source. CSS masking is often used in conjunction with CSS gradients, images, or other visual elements to create unique and interesting designs.
There are two main properties used for CSS masking:
mask-image
: Specifies the mask image or mask source that will be used for the masking effect.mask-mode
(optional): Defines how the mask image or source is blended with the content. The default value isalpha
, but other possible values includeluminance
,auto
,add
,subtract
, etc.
The mask-image
property can take one of the following values:
url()
: Specifies the URL of an image to be used as the mask source.none
: Removes any existing mask effect, making the element fully visible.linear-gradient()
: Defines a linear gradient that serves as the mask source.radial-gradient()
: Defines a radial gradient that serves as the mask source.element()
: Refers to another HTML element to be used as the mask source.
Example:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>CSS Masking Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="masked-element"></div>
</body>
</html>
CSS (styles.css):
.masked-element {
width: 200px;
height: 200px;
background-image: url('mask-image.png'); /* Replace with your mask image URL */
-webkit-mask-image: url('mask-image.png'); /* For older versions of webkit-based browsers */
mask-image: url('mask-image.png');
}
In this example, the .masked-element
is a square div with a size of 200px by 200px. We use the mask-image
property to apply a mask effect to the element using an image named “mask-image.png.” The mask image determines which parts of the element will be visible and which parts will be masked out.
Note that CSS masking may not be supported in older browsers, and it’s essential to check for browser compatibility before using it in production. Also, due to browser prefixes, it’s common to include both -webkit-mask-image
and mask-image
properties to ensure compatibility with different browsers.