Easy Color-changing SVG from CSS
Yesterday, by some weird metric of “Huh, why can’t I just do this?”, I managed to find a super-easy way to apply an SVG icon purely from CSS – including the ability to change its color – i.e. without having to embed the SVG code directly in the HTML.
It looks like this:
.iconlink {
color: blue;
}
.iconlink::after {
content: "";
display: block;
inline-size: 24px;
block-size: 24px;
background-color: currentcolor;
mask: url(icon-arrow.svg) center no-repeat;
}
So instead of applying the SVG as a background image, we create a block of color and use the SVG
as a mask. The result is a graphic in whatever color you’ve set as the background color, which can
be transitioned as usual. In the example here I use currentcolor
to have it take whatever color the
link is but it can be any color really – it could even be a gradient, huh?
I’m sure I’ll find out that someone else has done this before because it seems “almost too easy…”, but for now, I’m just super happy that I finally found a way to get around one of my highest ranking annoyances when doing frontend development.