Skip to Content Collective Idea Home

Photo from Unsplash. https://unsplash.com/license

Fun with SVG: Embedding in CSS

by Matt Slack

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.

Update

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.

Comments

Jaroslav Bereza
::

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


iDGS
::

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


Christoph Friedl
::

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: https://twitter.com/sarasoueidan/status/669499519252471809


Vadim Makeev
::

See “Optimizing SVGs in data URIs” article by Taylor Hunt, there’s a way to make it compatible: http://codepen.io/Tigt/post/optimizing-svgs-in-data-uris, there’s even PostCSS plugin for this https://github.com/TrySound/postcss-inline-svg