Using CSS variables in SVG icons

Florens Verschelde

When I started looking into SVG some three years ago, I envisioned this language as images separate from the page (like JPEG and PNG images are, unless you base64 them), that you could style, because it’s a document, right?

Except it doesn’t quite work like that. If you keep your SVG image as a separate document, you can’t modify it from the HTML document that calls it. I asked around more than two years ago; at the time there was a draft about SVG Params, and Tab Atkins suggested I look into CSS Variables (because future improvements to SVG styling-from-a-parent-document would probably use those). But CSS Variables were only implemented in Firefox and I didn’t manage to make the most of it.

Well, we now have CSS Variables in Firefox, Chrome and Safari, and coming to an Edge near you sometime in 2017. Plus we have collectively figured out that SVG’s <symbol> and <use> elements were a nice way to use SVG icons from the same HTML page or from an external symbol sprite, so maybe we can put the two together and it’ll just work?!

Quick demo (open in new tab):

In my tests it does work well in Firefox, Chrome and Safari (as long as they support CSS custom properties). Haven’t tried with Edge’s preview yet.

The funny thing is I had totally forgot that this would work. I was sure it wouldn’t for some shadowy Shadow DOM reason, and I actually forgot I had demonstrated it working last year. Duh.