Working with SVG icons
There have been a number of ways to work with icons on the web throughout the years. A long, long time ago, when phones flipped open and everyone was watching Lost, many websites used sprite sheets that mapped many graphical elements to one location in a larger image file. Having many elements share one file limited the number of http requests over the wire, which sped up page load times.
Around 2010 or so, sprite sheets started to fade in popularity and icon fonts became popular. They loaded in one file and used SVGs under the covers. Icon fonts allowed web graphics to scale, were lightweight, and were easy to style using CSS. Espalier does not use icon fonts. So, if icon fonts were so cool, why doesn't Espalier use them?
It turns out icon fonts are very bad for accessibility. Also, modern SVG files provide all the benefits of icon fonts without any of the drawbacks. SVG files can hold many distinct graphical elements. The key is to include them as symbols with an id, then reference them by id when they are used.
How does one go about creating an SVG sprite sheet?
Create an SVG file
This SVG file will hold many SVG icons. They will be added to the <defs> node.
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
</defs>
</svg>
Add SVG symbols
There are many resources for free and open source icons. Espalier has been using tabler icons. To add an icon to the SVG file:
- Go to tabler and click on an icon
- Click
Copy SVGto copy the raw SVG - Paste it into the defs section of the SVG file
- Rename the new
svgnode tosymbol - Delete the
xmlns,width,height, andclassattributes from the new symbol - Give the new symbol an
idattribute (maybe matching the tabler name) - Make sure the stroke is set to currentColor so it will adopt the foreground color of the Espalier element it is placed in
The SVG file now looks like this:
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<symbol id="brightness-2" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" /><path d="M6 6h3.5l2.5 -2.5l2.5 2.5h3.5v3.5l2.5 2.5l-2.5 2.5v3.5h-3.5l-2.5 2.5l-2.5 -2.5h-3.5v-3.5l-2.5 -2.5l2.5 -2.5z" />
</symbol>
</defs>
</svg>
Using the SVG
To use the SVG, it can be referenced by it's URL#id, as such:
<svg width="100" height="100">
<use href="/assets/icons.svg#brightness-2" />
</svg>