iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Masking

CSS masks use a second image — usually a black-and-white shape or a gradient — to control which parts of the element are visible.

The core properties

PropertyPurpose
mask-imageThe mask source — URL or gradient.
mask-modealpha (use transparency) or luminance (use brightness).
mask-size / mask-position / mask-repeatMirror their background-* equivalents.
-webkit-mask-*Prefix needed in Safari for the same set.

Fade out the bottom of an image

CSS
img.fade {
  mask-image:        linear-gradient(black 70%, transparent);
  -webkit-mask-image: linear-gradient(black 70%, transparent);
}

Cut a custom shape

CSS
.star {
  width: 120px; height: 120px;
  background: #04AA6D;
  mask: url('star.svg') no-repeat center / contain;
  -webkit-mask: url('star.svg') no-repeat center / contain;
}
Tip: Masks unlock recolourable icons: an SVG silhouette plus background-color gives you any colour you like with one icon file.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Masking</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Fade out the bottom of this image with a mask gradient.

img.fade { mask-image: linear-gradient(black %, transparent); }

Test yourself

Q1. Which property sets the mask source?
Q2. Which value of `mask-mode` uses brightness?
Q3. A common Safari prefix needed for masks is…

Discussion

Loading…