CSS Masking
CSS Masking allows you to hide parts of an element or image using a mask. This technique is used to control the visibility of an element, revealing only selected parts based on the mask.
Key Topics
Mask Image
The mask-image
property specifies the mask to be applied to an element, determining which parts are visible.
<style>
.mask-image {
width: 300px;
height: 200px;
background: url('example.jpg');
mask-image: url('mask-shape.png');
-webkit-mask-image: url('mask-shape.png');
}
</style>
<div class="mask-image"></div>
Explanation: The mask is applied to the image, revealing only the areas defined by the shape in mask-shape.png
.
Mask Size
The mask-size
property specifies the size of the mask image relative to the element.
<style>
.mask-size {
width: 300px;
height: 200px;
background: url('example.jpg');
mask-image: url('mask-shape.png');
-webkit-mask-image: url('mask-shape.png');
mask-size: 100px 100px;
-webkit-mask-size: 100px 100px;
}
</style>
<div class="mask-size"></div>
Explanation: The mask is resized to 100px by 100px, affecting how the masked content is displayed.
Mask Position
The mask-position
property specifies the position of the mask relative to the element.
<style>
.mask-position {
width: 300px;
height: 200px;
background: url('example.jpg');
mask-image: url('mask-shape.png');
-webkit-mask-image: url('mask-shape.png');
mask-position: center;
-webkit-mask-position: center;
}
</style>
<div class="mask-position"></div>
Explanation: The mask is centered on the element, aligning its position relative to the container.
Mask Repeat
The mask-repeat
property determines how the mask is repeated across the element.
<style>
.mask-repeat {
width: 300px;
height: 200px;
background: url('example.jpg');
mask-image: url('mask-shape.png');
-webkit-mask-image: url('mask-shape.png');
mask-repeat: no-repeat;
-webkit-mask-repeat: no-repeat;
}
</style>
<div class="mask-repeat"></div>
Explanation: The mask is applied once without repetition, ensuring only one mask shape is visible.
Combining Masks
You can combine multiple mask properties to create complex effects.
<style>
.mask-combination {
width: 300px;
height: 200px;
background: url('example.jpg');
mask-image: url('mask-shape.png');
-webkit-mask-image: url('mask-shape.png');
mask-size: 150px;
-webkit-mask-size: 150px;
mask-position: center;
-webkit-mask-position: center;
}
</style>
<div class="mask-combination"></div>
Explanation: This example combines mask-size
and mask-position
to align and resize the mask for a custom effect.
Key Takeaways
- Mask Image: Define a mask using the
mask-image
property. - Mask Size: Control the dimensions of the mask relative to the element.
- Mask Position: Adjust the alignment of the mask using
mask-position
. - Mask Repeat: Specify how the mask repeats over the element.
- Combinations: Combine properties for more intricate masking effects.