Reusing Components

Use the <use> component to reuse a component elsewhere.

For security reasons, browsers may apply same-origin policy on <use> elements and refuse to load a cross-origin URL in the href attribute (MDN).

SVG elements

<use>

Takes a node and duplicate them elsewhere.

Note that except for x, y, width, height and href attributes, you cannot override attributes already set on the original element.

  • href URL/fragment to the element to be duplicated
  • x top-left x coordinate to place the duplicated element
  • y top-left y coordinate to place the duplicated element
  • width width of the duplicated element (has no effect if the referenced element does not have a viewbox)
  • height height of the duplicated element (has no effect if the referenced element does not have a viewbox)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 10" width="200">
 <circle id="myCircle" cx="5" cy="5" r="4" stroke="blue"/>
 <!-- duplicate element, setting fill -->
 <use href="#myCircle" x="10" fill="blue"/>
 <!-- stroke is ignored here because it's already set -->
 <use href="#myCircle" x="20" fill="white" stroke="red"/>
  </svg>
| LIVE PREVIEW

<symbol>

Defines graphical template objects which can be instantiated by a <use> element. (Just for structure and semantics.)

View box
  • x x coordinate of the symbol
  • y y coordinate of the symbol
  • width width of the symbol
  • height height of the symbol
  • viewBox bounds of the SVG viewport, e.g. 0 0 80 20 (see View Box)
  • preserveAspectRatio defines how to fit the viewport if aspect ratio of the viewBox does not match the given width and height, e.g. xMidYMid meet (see preserveAspectRatio)
  • refX defines the x coordinate of the symbol (which is defined by the cumulative effect of the x attribute, any transformations on the <symbol>, and its host <use> element)
  • refY defines the y coordinate of the symbol (which is defined by the cumulative effect of the y attribute, any transformations on the <symbol>, and its host <use> element)
<!-- https://developer.mozilla.org/en-US/docs/Web/SVG/Element/symbol -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 20" width="300">
  <!-- Our symbol, using its own coordinate system -->
  <symbol id="myDot" width="10" height="10" viewBox="0 0 2 2">
    <circle cx="1" cy="1" r="1" />
  </symbol>
  <!-- A grid to materialize our symbol positioning -->
  <path d="M0,10 h80 M10,0 v20 M25,0 v20 M40,0 v20 M55,0 v20 M70,0 v20" fill="none" stroke="pink" />
  <!-- All instances of our symbol -->
  <use href="#myDot" x="5"  y="5" style="opacity:1.0" />
  <use href="#myDot" x="20" y="5" style="opacity:0.8" />
  <use href="#myDot" x="35" y="5" style="opacity:0.6" />
  <use href="#myDot" x="50" y="5" style="opacity:0.4" />
  <use href="#myDot" x="65" y="5" style="opacity:0.2" />
</svg>
| LIVE PREVIEW

References