Inlining SVG background images in CSS with custom properties
Here’s a tiny lesson that I picked up from Trys that I’d like to share with you…
I was working on some upcoming changes to the Clearleft site recently. One particular component needed some SVG background images. I decided I’d inline the SVGs in the CSS to avoid extra network requests. It’s pretty straightforward:
background-image: url('data:image/svg+xml;utf8,<svg> ... </svg>');
You can basically paste your SVG in there, although you need to a little bit of URL encoding: I found that converting
%23 to was enough for my needs.
But here’s the thing. My component had some variations. One of the variations had multiple background images. There was a second background image in addition to the first. There’s no way in CSS to add an additional background image without writing a whole
background-image: url('data:image/svg+xml;utf8,<svg> ... </svg>'), url('data:image/svg+xml;utf8,<svg> ... </svg>');
So now I’ve got the same SVG source inlined in two places. That negates any performance benefits I was getting from inlining in the first place.
That’s where Trys comes in. He shared a nifty technique he uses in this exact situation: put the SVG source into a custom property!
--firstSVG: url('data:image/svg+xml;utf8,<svg> ... </svg>');
--secondSVG: url('data:image/svg+xml;utf8,<svg> ... </svg>');
Then you can reference those in your
background-image: var(--firstSVG), var(--secondSVG);
Brilliant! Not only does this remove any duplication of the SVG source, it also makes your CSS nice and readable: no more big blobs of SVG source code in the middle of your style sheet.
You might be wondering what will happen in older browsers that don’t support CSS custom properties (that would be Internet Explorer 11). Those browsers won’t get any background image. Which is fine. It’s a background image. Therefore it’s decoration. If it were an important image, it wouldn’t be in the background.
Progressive enhancement, innit?
This was originally posted on my own site.