SVG sprite sheets, explained

Updated

An SVG sprite puts a whole icon set in one file: each icon is a <symbol>, and pages show an icon with a tiny <use> reference. One download, one cache entry, and every icon still styleable where it's used.

How a sprite works

A sprite is an SVG whose icons are wrapped in <symbol> elements with ids. A symbol is never drawn by itself — it's a template that <use> stamps out:

<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
  <symbol id="icon-home" viewBox="0 0 24 24">
    <path d="M3 11 12 3l9 8v10H3z" />
  </symbol>
  <symbol id="icon-user" viewBox="0 0 24 24">
    <circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" />
  </symbol>
</svg>
<svg width="24" height="24"><use href="#icon-home" /></svg>

Each symbol keeps its own viewBox, so icons drawn at different sizes all scale correctly into whatever box <use> gives them.

Inline or external

Inline the sprite once near the top of the page and reference icons as href="#icon-home", or keep it as a file and reference href="/sprite.svg#icon-home". The external file is cached across pages, but must be served from the same origin.

Styling sprite icons

Content drawn through <use> sits in a shadow tree, so page CSS can't reach individual paths inside it. Style it by inheritance instead: paint the symbol's shapes with currentColor (or leave fill unset) and set color or fill on the <svg> that holds the <use>.

The id problem

Icons exported separately often reuse the same internal ids — two icons that both define a gradient called "a". Merged into one sprite, the second icon silently uses the first icon's gradient. A sprite generator should prefix every internal id with its symbol's id and rewrite the references to it.