How to use SVG in CSS

Updated

Putting an SVG straight into a stylesheet saves a request and keeps small icons next to the styles that use them. There are two ways to encode it, one of which is clearly better, and one trick — CSS masks — that makes the icon follow the text colour.

URL-encoded or base64?

An SVG can go into url() as a data URI in two forms:

.a { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath d='M0 0h8v8z'/%3E%3C/svg%3E"); }
.b { background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4IDgiPjxwYXRoIGQ9Ik0wIDBoOHY4eiIvPjwvc3ZnPg=="); }

Prefer URL-encoding. Base64 makes the SVG about a third larger and turns readable markup into noise that gzip can barely compress, while a URL-encoded SVG stays close to its original size and compresses well. Base64 is still the right choice where a tool or API only accepts base64.

Encoding rules

  • Escape # and % (they would end or corrupt the URL), the quote character used around the url(), and line breaks — a CSS string can't span lines, so put the SVG on one line. Escaping < and > too is recommended.
  • Use single quotes inside the SVG when the url() uses double quotes, or the other way round.
  • Keep xmlns="http://www.w3.org/2000/svg" — without it, the image won't render.
  • Optimize the SVG first: every byte saved is saved in every stylesheet that includes it.

Icons that take the text colour: mask-image

An SVG used as a background keeps its own colours — it can't see the page's CSS, so currentColor doesn't work inside it. Use it as a mask instead and paint the element with background-color: the icon then takes any colour, including the current text colour:

.icon {
  width: 1em;
  height: 1em;
  background-color: currentColor;
  -webkit-mask: url("data:image/svg+xml,…") center / contain no-repeat;
  mask: url("data:image/svg+xml,…") center / contain no-repeat;
}

When to use a file or inline SVG instead

  • Large or detailed SVGs: a separate .svg file is cached once instead of re-downloaded with every stylesheet change.
  • Icons that need several colours controlled from CSS, or animation: inline the SVG in the HTML (or use a sprite with <use>).
  • Icons repeated across many rules: a CSS custom property holding the data URI keeps one copy.