SVG Sprite Guide: symbol, use, and What Actually Inherits
The modern sprite is one file full of <symbol> elements, referenced by
<use href="sprite.svg#icon">. It is worth doing, and the usual reason given for
it is wrong. Twelve 48-pixel icons cost 1,629 raw bytes as separate files and
1,426 as a sprite — a 203-byte difference — but 1,588 bytes gzipped against
374, because twelve gzip streams each spend about 130 bytes on a header before a single
path. The sprite wins on requests and on compression overhead. It does not win on markup,
and it quietly changes what your CSS can reach: colour and fill cross the boundary,
selectors do not.
The rest of this page is that sentence unpacked. Five sprite variants — symbols in an external file, symbols inlined into the page, a group-based sprite, the same symbols with the viewBox removed, and a sprite whose symbols declare no fill — with twelve icons each in a 48-pixel box. The numbers below come from Chrome 157.0.8103.79, with the server logging every request and a screenshot diff for the pixels.

The file that replaces twelve
A sprite is a normal SVG whose body is a list of <symbol> elements. Each
symbol is invisible until something references it, carries its own viewBox, and can
hold any markup a drawing can. The twelve icons here total 1,426 bytes and
374 gzipped, and the page that uses all twelve asks the server for the sprite exactly once —
the log shows one request for the file and none for the icons, because there are no icon files.
Compare the two alternatives. Twelve separate files: 1,629 raw, 1,588 gzipped across twelve streams, twelve requests, and the page that shows them added twelve URLs to the critical path. Symbols inlined into the page: 706 gzipped for the whole markup plus its twelve references, zero requests, and no way to share the cache with the next page. The external sprite sits at 389 bytes of page plus 374 bytes of sprite, so 763 on the first page and 389 on every page after it.
That last number is the actual argument. A sprite is a caching decision: pay once, reference everywhere, and keep the page's DOM to twelve two-element subtrees instead of twelve full drawings. If a site has exactly one page, inlining the symbols wins; if it has a header, a footer and a sidebar, the separate file pays for itself on the second page.
Why the compressed number moves so much
Gzip is a stream compressor, and each HTTP response is its own stream. A 130-byte icon compresses to a 130-byte body plus roughly 100 bytes of gzip header, flush markers and trailer, so twelve of them are 1,588 bytes for 1,629 bytes of drawing — a compression ratio close to 1. Put the same twelve drawings in one file and the compressor finds the shared structure of the markup: 1426 bytes in, 374 out, a ratio of 3.8 to 1.
This is the part of the sprite story that survives scrutiny. The "sprites reduce file size" claim is only true in the sense that matters — bytes on the wire after compression, and requests — and not in the sense people usually check, which is the size of the file on disk. Raw, the sprite is 203 bytes smaller; that is not a reason to restructure an icon system. 1,214 bytes and eleven requests are.
A symbol without a viewBox renders at half size
Every symbol in the test declares viewBox="0 0 24 24", and every icon is drawn
between 3 and 21 units. With the viewBox, a 48-pixel box scales 24 units to 48 pixels, so the icon
measures 32 to 36 pixels of ink depending on its shape. Remove the viewBox from the
symbols and the same twelve icons come out at 16 to 18 pixels — exactly half — pinned to the corner
of the box, because the units are now pixels and the 48-pixel box is twice the drawing.
The older convention makes this worse rather than better. A sprite built from
<g id="icon"> inside <defs> behaves the same way: a
<g> cannot carry a viewBox, so the reference draws at 1:1 in the
outer coordinate system. Measured against the same page, the group sprite was indistinguishable
from the symbol sprite without a viewBox — 16 pixels where 32 were wanted. If a sprite looks
"zoomed out" when you switch from inline SVG to a reference, this is the first thing to check: the
viewBox is on the original <svg>, which the sprite builder threw
away, and not on the <symbol> it created.
What crosses the shadow boundary
A <use> does not copy markup into your document; it draws a shadow tree. That
has three consequences, all visible in the measurements. First, the page cannot select the shapes
inside: a rule like .ic path { fill: #16a34a } painted zero green pixels, and
querySelectorAll on the host returns only the <use> element
itself. Second, inherited properties still arrive, because inheritance runs down the flattened
tree: setting color: #e11d48 on the host painted 976 pixels of the icon red through
currentColor, and putting fill="#0ea5e9" on the <use>
painted 756 pixels blue when the symbol declared no fill of its own. Third, a symbol that declares
fill="currentColor" keeps it — the declaration inside wins over anything the reference
inherits.
So the styling contract of a sprite is narrower than it looks: colour and fill are the two
channels that work, plus anything else inheritable (stroke,
stroke-width when not set inside, font-*, visibility).
Everything that needs a selector — a hover state on one path, a rule that recolours the second
shape — has to be written inside the sprite file, where it applies to every use of that symbol.
That is a limitation and also a guarantee: a sprite is the only way to have one definition of an
icon and no way for a page to fork it by accident.
External references are same-origin only
Point a <use> at a second local server and nothing happens. Both cross-origin
attempts — one plain, one serving Access-Control-Allow-Origin: * — produced zero
requests on the target server and the console line Unsafe attempt to load URL … from frame.
Chrome refuses before the fetch, so there is nothing for CORS to permit. The sprite has to be
served from the same origin as the page, which in practice means a relative path like
/assets/icons.svg.
Same-origin is also why a sprite on a CDN needs a proxy or a build step that inlines it: a cross-origin CDN URL will fail even with permissive headers. The security side of this mechanism — what a symbol can carry, and why a reference is not automatically safe — is covered in SVG <use> element security.
The cost: 400 references take twice as long to lay out
Sprites are not free at render time. Four hundred <use> elements in a grid
laid out in 4.9 ms (median of six runs, 4.5 to 6.7), against 2.4 ms (1.9 to 2.6) for four hundred
inline copies of the same rectangle. The reference has to be resolved and its shadow tree
instantiated for each use; the inline copy is just parsed markup. At twelve icons nobody will
notice 4.9 ms; at four hundred, the sprite is twice the layout cost of doing nothing clever.
Both numbers are small enough that the decision should be made on caching and on CSS, not on speed. If a page really has four hundred icons, it has a different problem — the icon grid should be one symbol drawn with a repeated pattern, or a font, or a canvas.
Building it
A sprite builder has four jobs: keep the viewBox, drop the wrapper, namespace the ids and remove
what does not belong in a symbol. The id step is not optional — two exports from the same design
tool will both contain id="a", and a sprite with two of them silently paints the
wrong gradient. Prefix on the way in, with a negative lookahead so #a does not match
#ab:
function prefixIds(svg, prefix) {
const ids = [...svg.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]);
let out = svg;
for (const id of ids) {
const safe = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
out = out.replace(new RegExp('(\\sid=")' + safe + '(")', 'g'), '$1' + prefix + id + '$2');
out = out.replace(new RegExp('#' + safe + '(?![\\w-])', 'g'), '#' + prefix + id);
}
return out;
}
With that, the build itself is a loop. Note the throw: a source file without a
viewBox cannot become a symbol that scales, and failing the build is better than shipping a sprite
that renders everything at half size.
function buildSymbols(icons) {
const parts = [];
for (const icon of icons) {
const box = /viewBox="([^"]+)"/.exec(icon.svg);
if (!box) throw new Error(icon.name + ': no viewBox');
const inner = icon.svg
.replace(/^[\s\S]*?<svg[^>]*>/, '')
.replace(/<\/svg>[\s\S]*$/, '')
.replace(/<!--[\s\S]*?-->/g, '');
parts.push('<symbol id="' + icon.name + '" viewBox="' + box[1] + '">' +
prefixIds(inner, icon.name + '-') + '</symbol>');
}
return '<svg xmlns="http://www.w3.org/2000/svg">' + parts.join('') + '</svg>';
}
Two details that are easy to miss. The wrapper's width and height are
dropped, because they belong to the outer <svg> and not to the symbol. And the
first <svg> tag is stripped with a lazy match up to the first >;
if a source file has an XML declaration or a doctype in front of it, that is removed by the same
expression, which is what you want — a sprite is not a standalone document.
Auditing it
A sprite rots in two directions: a page references an id that no longer exists, and a symbol
stops being referenced by anything. Both are invisible in a browser, because a missing
<use> renders nothing and an unused symbol renders nothing. One pass over the
built HTML catches both:
function auditSprite(sprite, pages) {
const symbols = [...sprite.matchAll(/<symbol[^>]*\sid="([^"]+)"/g)].map((m) => m[1]);
const known = new Set(symbols);
const used = [];
for (const html of pages) {
for (const m of html.matchAll(/<use\s[^>]*href="([^"]+)"/g)) {
used.push(m[1].split('#').pop());
}
}
const missing = [...new Set(used.filter((id) => !known.has(id)))];
const unused = symbols.filter((id) => !used.includes(id));
return { symbols: symbols.length, uses: used.length, missing, unused };
}
Run it in the build, not by hand. The failure it catches most often is the quiet one: an icon renamed in the design file, still referenced by a page nobody rebuilt, drawing an empty square that looks like a loading state. The same reachability question, one level deeper — which definitions inside a single file nothing references — is the subject of unused defs cleanup.
The checklist
- Put the viewBox on every symbol. A group cannot carry one, and a symbol without one draws at 1:1.
- Prefix every id while building. Two icons from one export will collide, and the collision is silent.
- Serve it same-origin. A cross-origin sprite is refused before the request, with or without CORS headers.
- Style through colour and fill. Selectors from the page cannot reach inside a
<use>; anything else belongs in the sprite file. - Audit both directions. Missing targets render as nothing; unused symbols cost bytes and render as nothing.
- Inline the symbols instead when there is one page. No request, no CORS, no cache to bust — and the same shadow-tree rules apply.
If the choice is between a sprite and an image tag rather than a sprite and inline markup, the
container matters more than the file: an SVG inside <img> cannot fetch anything
and cannot be styled at all, which is measured in
inline SVG versus the img
tag.
Related SVG Workflows
One file, many references — the same questions of reachability, naming and caching that every other SVG pipeline runs into.
- Inline SVG vs the img Tag — five containers, and the four things that stop at the frame.
- SVG <use> Element Security — what a symbol can carry and what a reference can fetch.
- Unused SVG defs Cleanup — finding definitions nothing reaches, with the same reachability walk.
- SVG viewBox vs width and height — why the box, not the file, decides the size.
- Why Is My SVG File So Large? — a byte audit of ten files that draw the same scene.
- Sandboxing an SVG Preview — what still loads when a drawing is isolated in a frame.
- SVG Validator — check ids, references and viewBoxes before the sprite is built.
Try These Free Online Tools
No download required — convert, compress & optimize SVGs right in your browser



