Color SVGs with a CSS mask

You can use a mask to change the color of a SVG in CSS. This is a nice solution for dynamically changing the color of an icon when the SVG can't be included in the DOM for whatever reason.

The syntax for masks is similar to that of background images. The effect of specifying a mask is, that only the parts of the element are visible, where the mask image is opaque.

Browser Support is quite good at point of writing: browsers based on webkit need vendor-prefixed properties, Firefox fully supports it.

Example:

:root {
--icon-color: rgb(0, 138, 214);
--icon-checkmark: url(./checkmark.svg)
}

.with-checkmark:before {
display: inline-block;
width: 1rem;
height: 1rem;
/* fallback for browsers that don't support mask */
content: var(--icon-checkmark);
}

@supports (mask-size: cover) or (-webkit-mask-size: cover){
.with-checkmark:before {
content: '';
mask: var(--icon-checkmark) no-repeat center;
-webkit-mask: var(--icon-checkmark) no-repeat center;
mask-size: cover;
-webkit-mask-size: cover;
/* the shape of the SVG will be visible in the background color */
background-color: var(--icon-color);
}
}

Another live example on CodePen:


This article has been published on on my blog. Here's a list of all articles if you're interested in this kind of stuff.