Fun with SVG: Embedding in CSS

Photo from Unsplash.

One of the best ways to deal with high density displays is to use vector images (specifically SVGs). And a good way to speed up load time is to reduce the number of HTTP requests. I’ve been doing this for quite a while with base64 encoded images. Unfortunately base64 increases the bytesize of your image by about 30% and it makes it a pain to edit your image after you’ve embedded it.

Recently it occurred to me that with SVG I should be able to specify an encoding other than base64, like say utf-8. Paste a raw SVG in your CSS as a background image (make sure to be consistent in your use of double or single quotes!), and it will Just Work. You can even keep your line breaks for easy reading/editing as long as you escape them.


As pointed out to the comments, this doesn’t quite just work in Firefox and IE.

Firefox seems to play a lot nicer if we don’t use hex colors (RGB and named colors work just fine). I haven’t managed to find the correct escaping to work in IE9 & 10, but IE11 works just great.

Photo of Matt Slack

Long a secret weapon at Collective Idea, Matt has been involved with Collective Idea projects since the beginning. He’s our resident web front-end master (webmaster?) who can knock out CSS and HTML faster than you can think.


  1. November 25, 2015 at 7:53 AM

    Does it works in FireFox? I can’t see result. I see only blue background.

    November 25, 2015 at 8:03 AM

    Ditto. Works in Safari, Chrome, but in Firefox and Opera (Mac) I just see the background color. No stars. :’-(

    Christoph Friedl
    November 25, 2015 at 8:21 AM

    The Hashtags have to be escaped to make it work in Firefox. For IE the whole string must be escaped.

    Thanks to Sara Soueidan for pointing that out:

  4. November 25, 2015 at 11:52 AM

    See “Optimizing SVGs in data URIs” article by Taylor Hunt, there’s a way to make it compatible:, there’s even PostCSS plugin for this