DEV Community

David Bushell
David Bushell

Posted on

Quick tip: SVG & CSS Masks

Did you know you can embed SVG inline of CSS using a custom property?

:root {
  --arrow: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M4 8a.5.5 0 0 1 .5-.5h5.793L8.146 5.354a.5.5 0 1 1 .708-.708l3 3a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708-.708L10.293 8.5H4.5A.5.5 0 0 1 4 8"/></svg>');
}
Enter fullscreen mode Exit fullscreen mode

The SVG can be reused and recoloured to match the current colour:

button::after {
  background: currentColor;
  mask: var(--arrow) center center / 100% auto no-repeat;
  content: "";
  display: block;
  height: 1rem;
  width: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

The key to this technique is using mask instead of background-image. This allows you to change colours and even transition!

See my CodePen demo for an interactive example and my original blog post for further details of this technique.

Happy coding!

Top comments (0)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay