SVG Sprite with the <use> Element

Master the SVG <use> element for referencing sprite symbols. Learn about href vs xlink:href, sizing, styling inheritance, and shadow DOM behavior in modern browsers.

Concepts

Detailed Explanation

The SVG <use> Element

The <use> element is the mechanism that makes SVG sprites practical. It creates a rendered instance of a <symbol> defined elsewhere in the document or in an external file. Understanding how <use> works is essential for effective sprite usage.

Basic Syntax

<svg width="24" height="24" aria-hidden="true">
  <use href="#icon-name"/>
</svg>

The href attribute points to the id of a <symbol> in the current document. The outer <svg> tag controls the rendered dimensions.

href vs xlink:href

Historically, SVG used xlink:href from the XLink namespace. Modern browsers (all evergreen browsers since ~2018) support the simpler href attribute directly. However, for maximum compatibility you may see both:

<!-- Modern (recommended) -->
<use href="#icon-name"/>

<!-- Legacy compatibility -->
<use xlink:href="#icon-name"/>

<!-- Both (belt and suspenders) -->
<use href="#icon-name" xlink:href="#icon-name"/>

Sizing and Scaling

The <use> element inherits the viewBox from its referenced <symbol>. The outer <svg> width and height determine the rendered size. You can also use CSS to control sizing:

.icon {
  width: 1.5em;
  height: 1.5em;
}
<svg class="icon"><use href="#icon-name"/></svg>

Style Inheritance

Styles applied to the outer <svg> or <use> element cascade into the cloned content, but with an important caveat: <use> creates a shadow DOM clone. This means:

  • CSS currentColor works — if the symbol uses fill="currentColor", setting color on a parent element controls the icon color
  • Direct CSS selectors do not penetrate — you cannot target individual paths inside a <use> reference from external CSS
  • Presentation attributes on the symbol win — if a path has fill="#ff0000" hardcoded, CSS cannot override it through <use>

This is why stripping fill and stroke attributes from source SVGs is so important for sprite systems.

External File References

You can reference symbols from a separate SVG file:

<svg width="24" height="24">
  <use href="sprites.svg#icon-name"/>
</svg>

This enables browser caching of the sprite file. Note that external references may not work with file:// protocol or in some IE/Edge legacy browsers.

Use Case

Developers implementing icon systems with SVG sprites who need to understand the nuances of the <use> element, particularly around styling, sizing, and cross-browser compatibility.

Try It — SVG Sprite Generator

Open full tool