Skip to content

I use SVGs for just about anything I can get away with — logos, icons, spinners, the odd decorative flourish. A lot of them end up in CSS as a background-image, and that is where it stops being straightforward, because you cannot simply paste an SVG into a stylesheet and hope for the best.

Why it needs encoding at all

An ordinary SVG straight out of Illustrator or Figma contains at least three things that will quietly break a CSS url():

  • A hex colour. The # in #00304b starts a fragment identifier as far as the URL parser is concerned, so everything after it is thrown away and you get nothing.
  • Double quotes around the attributes, which close the CSS string early and take the rest of your declaration with them.
  • Angle brackets, and the curly braces of any <style> block inside the SVG, which parsers are entitled to be suspicious of.

On top of that there is the guff at the front — the XML prolog, a doctype, and whatever comment your editor felt like leaving behind. None of it does anything in a data URI except make the line longer.

The tool

So here it is. Paste an SVG in and it drops everything before the opening tag, collapses the whitespace, swaps the double quotes for single ones, and escapes only the handful of characters that genuinely have to be escaped. You get the encoded string, a background-image line ready to paste, and a preview swatch painted with the encoded URI itself — so if that square is empty, the string is broken.

If your SVG has any hex colours in it, a picker appears for each one. That was on the roadmap in the original version of this post back in 2018 and I never got round to it, so: better late than never.

What changed since I first wrote this

This is a rewrite. The first version of this post was from 2018 and it was mostly about Internet Explorer, which used to get particular about quotes inside url(). IE was retired in 2022 and I have not missed it.

The old tool ran the whole SVG through encodeURIComponent. That was the sensible, bulletproof choice while IE was still in the support matrix, but it escapes every space and every slash as well as the characters that actually matter — so the strings came out about a third longer than they needed to be. On a typical icon the new version is roughly 35% smaller. The single quotes are deliberate too: they are perfectly valid XML, and they mean you can still read what the SVG is when you trip over it in a stylesheet a year later.

It also lives here in the post now, rather than on a page of its own that I would inevitably forget to keep alive.