No one likes those big articles - that’s why we’re creating Quick Tips - short tips to change your developer's life from the moment you read them. Those may be some patterns explained in JS code on real-life examples or some techniques for better code.
Let’s suppose you are in need of color-changing icons or some fancy-shaped photo container, but you really don’t like this messy SVG markup in your code. Say no more!
What if I told you both of these things could be done with CSS only, without embedding your SVG code in HTML? CSS Mask - the hero we need and deserve.
How does that work?
Basically, we still need to store this SVG image somewhere. What we don’t need is looking inside or doing anything with its code. We simply use it as a mask like that:
- Ok, that’s cool, but I don’t see any changes…
Hell yeah, you don’t. We still need to apply a background color to our div/pseudo element or fill it with an image, so that our mask actually masks something. Let’s try it in a real life example.
First things first - HTML and some basic styling:
<div class="icon icon--unicorn"></div>
<div class="list__txt">Unicorns exist</div>
<div class="icon icon--narwhal"></div>
<div class="list__txt">Just like narwhals</div>
border: 1px solid #dce2eb;
box-shadow: 0 10px 30px 0 rgba(161, 172, 217, 0.3);
Now let’s handle our icon and mask.
transition: background-color 0.2s ease-out;
Almost there... Now you should see something like this.
…and since our icon’s color is determined outside of the SVG file by CSS background-color, we can simply use a transition on hover to change it, so it works like this:
And that’s it!
No need to mess with SVG fills, strokes, adding classes or anything. Just our old HTML and CSS.