EthicsComputerCourses
Join training +91 90532 10052

CSS Masking

CSS · Lesson 113 of 240 Intermediate 11 min read Updated

By the end of this lesson you will be able to fade the edges of a scrolling strip, turn an SVG shape into a reusable stencil, build a star rating and a ticket with cut-out notches, and choose between alpha and luminance masks. You will also know when a mask is the right tool and when clip-path is simpler.

You met masks briefly in CSS Clip-Path. This lesson goes deeper. It assumes you know gradients from CSS Gradients and the background layer properties from Background Size & Attachment, because mask properties work in almost the same way.

How a mask works

A mask is an image that decides how much of an element is visible at each point. Think of the stencils used to paint shop names on walls in many Indian towns. The painter holds a cut-out sheet against the wall and sprays. Paint passes through the holes and is blocked everywhere else. A CSS mask is a stencil with one extra power: it can be partly see-through, so the paint can fade.

The browser paints the element as usual, then checks the mask image point by point:

  • Where the mask is fully opaque, the element shows completely.
  • Where the mask is fully transparent, the element is hidden.
  • Where the mask is half transparent, the element shows at half strength.

The colour of the mask does not matter in this default mode. Only its alpha (transparency) counts. That is why people write masks with black and transparent: black is simply an easy fully opaque colour.

Three facts are worth remembering early:

  • A mask never changes layout. The element keeps its full box size.
  • A mask does not change hit-testing, so invisible masked-out areas can still receive clicks. Clipped-out areas of clip-path do not.
  • Any mask-image other than none creates a new stacking context, just like opacity below 1 (see Z-Index & Stacking Context).

Gradient masks: fading the edges of a scroller

A gradient is an image, so it can be a mask with no file needed. A common use is a horizontal strip that scrolls sideways, such as the list of recent matches on a cricket site. Fading both ends tells the reader "there is more this way".

Step 1: build the scroller. Step 2: add one gradient mask that is transparent at both edges and solid in the middle.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Fading scroller edges</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; background: #f1f5f9; }
    .matches {
      display: flex;
      gap: 0.75rem;
      overflow-x: auto;
      padding: 0.5rem 2rem;
      /* Step 2: transparent at the ends, solid between 2rem and (100% - 2rem) */
      -webkit-mask-image: linear-gradient(to right, transparent, black 2rem, black calc(100% - 2rem), transparent);
      mask-image: linear-gradient(to right, transparent, black 2rem, black calc(100% - 2rem), transparent);
    }
    .match {
      flex: 0 0 11rem;
      padding: 0.75rem;
      border-radius: 10px;
      background: white;
      box-shadow: 0 1px 3px rgb(0 0 0 / 15%);
    }
    .match strong { display: block; }
  </style>
</head>
<body>
  <h2>Recent matches</h2>
  <div class="matches" tabindex="0" aria-label="Recent matches, scroll sideways">
    <div class="match"><strong>Pune vs Kochi</strong>Pune won by 6 wickets</div>
    <div class="match"><strong>Jaipur vs Lucknow</strong>Jaipur won by 18 runs</div>
    <div class="match"><strong>Rohtak vs Pune</strong>Match tied</div>
    <div class="match"><strong>Kochi vs Jaipur</strong>Kochi won by 3 wickets</div>
    <div class="match"><strong>Lucknow vs Rohtak</strong>No result, rain</div>
  </div>
</body>
</html>

What you should see: the cards fade out softly at the left and right edges, and they fade in as you scroll them into the middle. The side padding of 2rem matches the fade length, so the first and last cards can scroll fully into the solid area. Remove the two mask lines and run again to compare.

Mask size, position and repeat

Every background layer property has a mask twin with the same values: mask-size, mask-position, mask-repeat, mask-origin and mask-clip. Their initial values are also similar: the mask repeats, starts at the top-left (0% 0%) and uses its natural size (auto). A gradient has no natural size, so it fills the whole box unless you give it one.

An SVG file or a data: URL can supply a shape. Here a single star is drawn as SVG and repeated five times with mask-repeat: repeat-x. A hard-stop gradient behind it fills part of the stars, which gives a star rating. The second element is a cinema ticket with two round notches, made with two mask layers.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SVG masks, size and repeat</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; background: #fffbeb; }
    .stars {
      --rating: 70%;   /* 3.5 out of 5 */
      width: 10rem;
      height: 2rem;
      background: linear-gradient(to right, #f59e0b var(--rating), #cbd5e1 var(--rating));
      -webkit-mask: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M12 2l3 6.6 7 .7-5.3 4.8 1.6 7L12 17.5 5.7 21.1l1.6-7L2 9.3l7-.7z'/></svg>") 0 0 / 2rem 2rem repeat-x;
      mask: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M12 2l3 6.6 7 .7-5.3 4.8 1.6 7L12 17.5 5.7 21.1l1.6-7L2 9.3l7-.7z'/></svg>") 0 0 / 2rem 2rem repeat-x;
    }
    .ticket {
      width: 16rem;
      margin-top: 1.5rem;
      padding: 1rem 1.5rem;
      color: white;
      background: #be123c;
      /* two layers: a hole on the left half and a hole on the right half */
      -webkit-mask:
        radial-gradient(circle at left, transparent 0.9rem, black 0.95rem) left / 51% 100% no-repeat,
        radial-gradient(circle at right, transparent 0.9rem, black 0.95rem) right / 51% 100% no-repeat;
      mask:
        radial-gradient(circle at left, transparent 0.9rem, black 0.95rem) left / 51% 100% no-repeat,
        radial-gradient(circle at right, transparent 0.9rem, black 0.95rem) right / 51% 100% no-repeat;
    }
  </style>
</head>
<body>
  <p>Tunday Kebabs, Lucknow</p>
  <div class="stars" role="img" aria-label="Rated 3.5 out of 5"></div>
  <div class="ticket">
    <strong>Screen 2, Row F, Seat 11</strong><br>
    Saturday 7:30 pm, ₹220
  </div>
</body>
</html>

What you should see: three and a half orange stars, the rest grey, and a red ticket with a half-circle bite out of each side. Change --rating to 40% to get two stars.

Notice three things in the code:

  • The mask shorthand works like background: image, then position, then / size, then repeat.
  • Each comma starts a new mask layer. Each ticket layer covers just over half the ticket, so the two halves meet in the middle.
  • The star's SVG has no fill, so it is black, and its empty corners are transparent. In a data: URL, quote the whole URL with double quotes and use single quotes inside the SVG.

SVG files also keep their aspect ratio by default. If you set mask-size: 4rem 2rem on a square icon, the shape is centred inside that area instead of being stretched.

Alpha or luminance: mask-mode

mask-mode decides which part of the mask image counts.

ValueWhat countsVisible where the mask is
alphaTransparency onlyOpaque, whatever the colour
luminanceBrightness, multiplied by alphaBright and opaque
match-source (initial)alpha for images and gradients, luminance for an SVG <mask> elementDepends on the source

Luminance is useful when your mask has no transparency, such as a black and white image. White areas show the element, black areas hide it, and greys show it partly.

The sample icon below is an indigo rounded square with a yellow star, transparent only outside the rounded corners.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Alpha vs luminance masks</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; display: flex; flex-wrap: wrap; gap: 1.5rem; }
    figure { margin: 0; text-align: center; }
    .box {
      width: 8rem;
      height: 8rem;
      background: linear-gradient(135deg, #16a34a, #0e7490);
      -webkit-mask-image: url("https://course.ethicscomputer.in/assets/samples/icon.svg");
      mask-image: url("https://course.ethicscomputer.in/assets/samples/icon.svg");
      -webkit-mask-size: 100% 100%;
      mask-size: 100% 100%;
    }
    .luminance { mask-mode: luminance; }
  </style>
</head>
<body>
  <figure><img src="https://course.ethicscomputer.in/assets/samples/icon.svg" alt="Star icon" width="128" height="128"><figcaption>The mask image</figcaption></figure>
  <figure><div class="box"></div><figcaption>alpha (default)</figcaption></figure>
  <figure><div class="box luminance"></div><figcaption>luminance</figcaption></figure>
</body>
</html>

What you should see: with alpha, the green box takes the rounded square shape and the star disappears completely, because both colours are fully opaque. With luminance, the bright yellow star shows clearly, while the dark indigo square shows only faintly. The colours inside the box are always the element's own green gradient, never the icon's colours.

Safari has a known bug here: when the mask source is an SVG <mask> element, it uses alpha instead of luminance. Masks from image files and gradients work as expected.

Combining layers with mask-composite

When there are several mask layers, mask-composite decides how each layer combines with the layers below it:

  • add (initial): visible where any layer is visible.
  • subtract: the upper layer cuts a hole in the lower one.
  • intersect: visible only where both layers are visible.
  • exclude: visible where exactly one layer is visible.
CSS
/* a square card with a round hole punched in the centre */
.punched {
  mask:
    radial-gradient(circle, black 2rem, transparent 2.05rem),
    linear-gradient(black, black);
  mask-composite: exclude;
}

The old prefixed property -webkit-mask-composite uses different keywords, such as source-in and xor, so do not copy the standard values into it.

Masking or clip-path?

mask-imageclip-path
EdgesHard or softAlways hard
Shape comes fromAny image, SVG or gradientA shape function or SVG <clipPath>
Repeat and tileYes, with mask-size and mask-repeatNo
Clicks in hidden areasStill receivedNot received
Animationmask-position, mask-sizeBetween shapes of the same type

Use clip-path for crisp geometric cuts, such as circles, polygons and slanted sections. Use a mask when you need a fade, a shape from an image, or a repeating pattern.

Browser support and the -webkit- prefix

Unprefixed masking is Baseline 2023. It works in Chrome and Edge 120 (December 2023), Firefox 53 and Safari 15.4, and it became Baseline widely available in June 2026. The -webkit-mask-* properties are still accepted by all current browsers, Firefox included.

You need the prefix only for browsers older than those versions, such as Chrome before 120 or Samsung Internet before 25. Then write the prefixed line first and the standard line after it, as the examples do. A browser that understands both uses the last one.

Common mistakes

  • Using colours to control a default mask. In alpha mode a red mask and a black mask give the same result. Use transparency.
  • Forgetting no-repeat. A small SVG mask repeats by default, so one icon becomes a tiled pattern.
  • A mask file from another site. Without cross-origin permission the mask is dropped. Use your own files or data: URLs.
  • Hiding content with a mask and expecting no clicks. Hidden areas can still be clicked. Use clip-path, visibility or pointer-events if that matters.
  • Putting the -webkit- line last. It then wins in modern browsers too, and any standard-only values are lost.

Interview questions

1. How does a CSS mask decide what is visible?

The browser multiplies each painted point of the element by the mask value at that point. In alpha mode the mask's transparency is used, so opaque areas show the element and transparent areas hide it. In luminance mode the brightness of the mask is used, multiplied by its alpha.

2. What is the difference between mask-image and clip-path?

clip-path cuts the element with a geometric shape and always gives hard edges. mask-image uses an image or gradient, so it can fade and can repeat like a background. Clipped-out areas stop receiving pointer events, while masked-out areas still receive them.

3. When would you use mask-mode: luminance?

When the mask source has no useful transparency, such as a black and white image or a shape exported on a solid background. Bright parts then show the element and dark parts hide it. For images and gradients the default match-source gives alpha.

4. Do you still need -webkit-mask today?

Unprefixed masks are Baseline 2023, supported from Chrome 120, Firefox 53 and Safari 15.4. The prefix is only needed for older browsers. If you add it, put it before the standard property so the standard one wins.

5. Why might a mask image load in the browser but have no effect?

Mask images from URLs are fetched in CORS mode. If the file is on another origin without cross-origin headers, the browser refuses to use it. Serving the file from your own site or using a data: URL fixes it.

Key points

  • A mask is an image used as a stencil: opaque shows the element, transparent hides it, half-transparent fades it.
  • Gradients make file-free masks, ideal for fading text and scroller edges.
  • mask-size, mask-position, mask-repeat and the mask shorthand work like the background properties.
  • mask-mode chooses alpha or luminance; match-source uses alpha for images and gradients.
  • Several comma-separated layers combine with mask-composite: add, subtract, intersect, exclude.
  • Masks do not change layout or hit-testing and they create a stacking context.
  • Unprefixed masks are Baseline 2023; add -webkit- lines first only for older browsers.

Exercise

Build a "Today's specials" strip for a chai shop in Jaipur:

  • a horizontal row of at least five item cards that scrolls sideways, with both edges faded by a single gradient mask;
  • under it, a heart-shaped "favourite" badge made by masking a gradient <div> with an SVG heart in a data: URL (set no-repeat and contain);
  • a short comment in your CSS that explains why the heart is visible even though the SVG has no fill.
Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Today's specials</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    .specials {
      display: flex; gap: 0.75rem; overflow-x: auto; padding: 0.5rem 2.5rem;
      -webkit-mask-image: linear-gradient(to right, transparent, black 2.5rem, black calc(100% - 2.5rem), transparent);
      mask-image: linear-gradient(to right, transparent, black 2.5rem, black calc(100% - 2.5rem), transparent);
    }
    .item { flex: 0 0 9rem; padding: 0.75rem; border-radius: 10px; background: #ffedd5; }
    .fav {
      width: 3rem; height: 3rem; margin-top: 1rem;
      background: linear-gradient(135deg, #f43f5e, #be123c);
      /* No fill means black, which is fully opaque, so the heart shows */
      -webkit-mask: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M12 21s-8-5.2-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 10c0 5.8-8 11-8 11z'/></svg>") center / contain no-repeat;
      mask: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M12 21s-8-5.2-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 10c0 5.8-8 11-8 11z'/></svg>") center / contain no-repeat;
    }
  </style>
</head>
<body>
  <div class="specials" tabindex="0" aria-label="Today's specials, scroll sideways">
    <div class="item">Masala chai ₹20</div>
    <div class="item">Kulhad chai ₹30</div>
    <div class="item">Ginger lemon tea ₹25</div>
    <div class="item">Bun maska ₹35</div>
    <div class="item">Pyaaz kachori ₹30</div>
  </div>
  <div class="fav" role="img" aria-label="Favourite"></div>
</body>
</html>

One gradient handles both faded edges. The heart's path is black by default, and only the alpha of the mask matters, so the gradient shows through the heart and nowhere else.

Quick Quiz

1. In the default alpha mode, what does a solid red area in a mask do?

2. Which value of mask-mode uses the brightness of the mask image?

3. A small SVG mask appears as a tiled pattern across a large element. What is missing?

4. Which statement about masks and clip-path is true?

5. You support Chrome 115. How should you write the mask?

Learn CSS with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call