A little while ago I started using SVG for icons and needed to customize the style of specific SVG elements in a referenced SVG document depending on:
- Context. Where the icon is used and what the surrounding styles are.
- User interaction. Especially hover, focus and active states.
I also needed something that can work for both icons referenced from HTML (e.g. with an
<img> element) and from CSS (mostly as a
background-image). Currently there are some solutions for HTML, which require inlining the SVG glyphs and using
<svg><use xlink:href="…" /></svg>, and nothing for CSS (except SVG stacks which requires carefully planning the different styles in the original SVG file, duplicating elements, etc.).
It would be great to be able to use the power of SVG-with-CSS for referenced SVG documents as well.
Perhaps a solution should be added to the SVG Integration spec effort?
Idea: with CSS vars?
A little while ago I wrote Let’s dream: customizing SVG images with CSS Variables. The idea is that CSS variables defined or inherited on an element would be passed to any SVG document referenced by that element, be it as a
I meant to update that post for the past few weeks but I thought I’d rather present the idea here and ask for your feedback, and see if you might think up alternative solutions.
Why not icon fonts?
A common solution for the use-cases described above and in the above link is icon fonts. Sadly icon fonts are a hack, and have the same kind of accessibility issues as using CSS backgrounds to represent content (especially icon-only buttons or links). There are efforts right now to make icon fonts more usable for designers and developers, but not particularly more accessible (or less hackish).
The total lack of a simple accessibility mechanism such as
<img alt="…"> makes icon fonts fundamentally inaccessible (and mapping to vaguely relevant unicode characters is a laughable “solution”… try it with a screen reader).
Example from this very site
If I disable author
font-family declarations in my browser (“Allow pages to choose their own fonts, instead of my selection above”), this is what the main menu for this website looks like:
http://fvsch.com/temp/icon-fonts.png [can’t inline the image as a new user]
Icons are implemented with the FontAwesome icon font. This implementation breaks with no sensible fallback if users don’t allow fonts, or if the font file was not loaded for any reason (unreliable and/or slow network anyone?).
<img src="the_svg_file" alt="…"> instead, we’d still have the icons. And with images turned off, we could have text alternatives reading, e.g.:
[Name] | Notifications | Search | Go To | Account
The main issues with using
<img> here with SVG are:
- HTTP optimization. For raster images, commonly fixed with image sprites (introducing accessibility issues). For SVG, probably fixed by either HTTP2 or SVG stacks.
- Style customizations, which awaits a sensible solution (as far as I know).