Add SVG icons
- Author Benjy Stanton
- Date (updated 5 April 2021)
- Categories
Switching from PNGs (Portable Network Graphics) or icon fonts, to SVG (Scalable Vector Graphics) icons.
SVGs are best for icons
- SVGs are vector images
- They can be zoomed without pixelating
- Inline SVGs can be styled with CSS
- Inline SVGs are good for performance
- SVGs have accessibility advantages
- They are better than icon fonts
- Browser support is good
- Editable using code or vector drawing applications
Useful SVG attributes
height=""
width=""
viewBox=""
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
focusable="false"
aria-labelledby=""
fill="currentColor"
Add focusable="false"
to SVGs
Scott O'Hara explains why and when to use focusable="false"
focusable="false"
is also used to ensure Internet Explorer won’t allow the Tab key to navigate into the SVG.
Inline SVG performance benefits
- There is one less http request because we don't need to load an external image file
- File size is often smaller (unless the icon very complex)
- Only load what you need (instead of a whole icon font)
Related links
- Using ARIA to enhance SVG accessibility from The Paciello Group
- Seriously, Don’t Use Icon Fonts from Tyler Sticka
- Tips for Creating Accessible SVG from SitePoint
- SVGOMG from Jake Archibald
- SVG Path Visualizer from Mathieu Dutour
- SVG Export: Download SVGs from any site with ease
- Icon accessibility and aria label from Go Make Things
- Smashing Newsletter: SVG generators and tools
- Swipey image grids
What I changed on the blog
Old HTML
<i class="icon icon-social icon-instagram">
<span class="visuallyhidden">Instagram</span>
</i>
New HTML
<span class="icon">
<svg height="25" width="25" viewBox="0 0 25 25" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" focusable="false" aria-labelledby="iconTwitterTitle">
<title id="iconTwitterTitle">Twitter icon</title>
<path d="M7.8 22.6c8 .1 14.6-6.3 14.6-14.3v-.9c1-.7 1.8-1.6 2.5-2.7-.9.4-1.9.7-3 .8a4.7 4.7 0 0 0 2.2-2.8c-1 .6-2.1 1.1-3.2 1.3a5.1 5.1 0 0 0-7.3-.2c-1 1-1.6 2.3-1.6 3.7l.1 1.1C8.2 8.4 4.4 6.5 1.7 3.3a5 5 0 0 0 1.5 6.8c-.7 0-1.5-.2-2.2-.6v.1c0 2.4 1.7 4.6 4.1 5.1-.7.2-1.5.2-2.3.1a5 5 0 0 0 4.8 3.5 10.5 10.5 0 0 1-6.4 2.2H0c2.3 1.4 5.1 2.1 7.8 2.1"/>
</svg></span>