A pocket-sized guide to using SVG icon sprites in web apps
There are many ways to handle icons — over the last few years we went through PNG sprite maps, icon fonts, and more recently, SVG embeds. Taking it one step further, let me show you a simple, yet powerful, vector-based technique.
- Start with exporting each of the icons using the same artboard size (e.g: 128x128):
- Run the icons through svgo to compresses them:
- Add a title element to each icon for accessibility — screen readers will read this:
- Create an SVG within the body element and hide it from view using CSS.
- Each of your icons should be placed into seperate symbol element within the SVG container:
Now, from anywhere in the application, you can create an SVG container, and reference icons via use and the ID of your symbol.
- Make a helper, directive or a component so it’s easy as use:
- Wooooo! Now it’s time to add some colours ✨ Setting currentColor on the fill and stroke means that your icon will inherit the colours from the parent element. Radical. (🌈 You could set the fill to a gradient too).
Review the output and automate
Illustrator and Sketch both export all sorts of junk (Skeeeetch! 👀👊💥)
SVGO will compress that, but sometimes you’ll need to dig in and remove clips, masks or image embeds. Take a second or two to review the output.
Automate it! There’s bound to be a <insert tool here> helper to do this. I’ve had great success with this webpack loader by Stas Kurilov.
🍹 You’re now a SVG-Icon-baller. Enjoy!