Coloring icons with CSS mask-image

You can't set fill on a background SVG — but you can use the icon's shape as a mask and paint it with background-color. This recolors even an external SVG file, no inlining required.

The technique

.icon {
  display: inline-block;
  width: 24px; height: 24px;
  background-color: currentColor;      /* the icon color */
  -webkit-mask: url(star.svg) center / contain no-repeat;
  mask: url(star.svg) center / contain no-repeat;
}

The SVG's opaque areas become visible; the background-color shows through them. Swap the colour (including on hover or in dark mode) and the icon recolors instantly.

When to use it

  • Coloring icons you load as files, not inline SVG.
  • Pseudo-element icons (::before/::after).
  • Utility/icon plugins that generate mask-based classes.

Gotchas

Masking discards the icon's own colours, so it only suits single-colour icons — a multicolour emoji-style icon becomes one flat shape. Keep the -webkit- prefix for broad support.

Frequently asked questions

Can I recolor a multicolor SVG with mask?

No — masking flattens it to one colour. Use inline SVG to keep multiple colours.

Why use mask instead of inline SVG?

To recolor an external, cached SVG file without embedding its markup in the page.