Making your SVG icons CSS masks instead of inline HTML or backgrounds has some benefits

I’m a fan of just chucking SVG icons right into the HTML where you need them:

<svg class="icon icon-eye-dropper" width="16" height="16" viewBox="0 0 16 16">
  <path d="..." />
  <path d="..." />
</svg>Code language: HTML, XML (xml)

This has lots of benefits, like instant loading with no additional requests, and is 100% styleable, including all the internal parts (i.e. multicolor icons).

But, putting your SVG icons in CSS can be advantageous too. This converter is handy. For example:

.icon-menu {
  width: 1rem; height: 1rem;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="" width="16" height="16" viewBox="0 0 16 16"><path d="..."/></svg>');
}Code language: CSS (css)

You give up some styling control there — the icon is just going to look how that SVG looks, barring stuff like filter and background-blend-mode.

The advantage here is that your icons are now cached within your CSS and shared across everywhere on your site that is using that CSS file. If you have the (rare) issue of your DOM being too big, this would help.

A minor alteration to this is to use a mask instead of background-image to show the icon. This actually frees up the background to use to color it. Still getting the caching, just a bit easier to style now.

David Bushell just blogged about this and says:

This is technique perfect for:

  • Button icons
  • List bullet points
  • Custom checkbox icons

Especically when the icon changes colour depending on interactive state, or light and dark theming, for example.

Leave a Reply

Your email address will not be published. Required fields are marked *