Reusing SVG Elements with the SVG Use Tag

The <use> element in SVG provides a mechanism for duplicating and instantiating graphical objects across an SVG document. By referencing predefined elements or source graphics through an identifier, the <use> tag eliminates redundant code, drastically reduces file size, and streamlines the maintenance of vector graphics.

How the <use> Element Works

The <use> element acts as a clone mechanism. It takes nodes defined elsewhere in the document—or in an external SVG file—and renders them at a specified location.

Instead of redrawing complex shapes or paths repeatedly, you define the source graphic once, assign it a unique id, and reference it using the href attribute (or xlink:href in older SVG specifications).

<svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
  <!-- Define reusable assets without rendering them directly -->
  <defs>
    <circle id="base-circle" cx="0" cy="0" r="20" fill="teal" />
  </defs>

  <!-- Reuse the circle in different positions -->
  <use href="#base-circle" x="40" y="50" />
  <use href="#base-circle" x="100" y="50" />
  <use href="#base-circle" x="160" y="50" />
</svg>

The Role of <defs>

While <use> can clone visible elements on the canvas, it is most commonly paired with the <defs> (definitions) element. Elements placed inside <defs> are stored in memory but are not rendered visually until they are explicitly called by a <use> element. This creates a clean separation between asset definition and asset rendering.

Positioning and Transformation

Cloned elements can be placed and transformed independently of their source definition. The <use> element accepts:

Shadow DOM and Style Inheritance

When a <use> element references an object, the browser clones that object into a “closed” shadow tree attached to the <use> node. Understanding this behavior is critical for styling:

  1. Inherited Styles: If the source element lacks explicit styling (such as inline fill or stroke), it inherits the styles defined on the <use> element or its parent.
  2. Locked Styles: If an element inside the <defs> block has an explicit fill or stroke assigned directly to its attributes, the <use> tag cannot override those properties.
  3. Dynamic Theming with currentColor: Setting fill="currentColor" on the source graphic allows each <use> instance to adopt the CSS color property of its context, enabling versatile theming for icons and UI components.

Key Benefits