Use SVG symbol


Let’s say you have the following SVG:

<svg>
  <circle cx="20" cy="20" r="20" fill="red" />
</svg>

How can you re-use it multiple times in the same document without duplicating it?

With symbol, you can do so via template objects.

Example

Wrap the shape with <symbol> and set an id on it:

<svg>
  <symbol id="circle">
    <circle cx="20" cy="20" r="20" fill="red" />
  </symbol>
</svg>

Then with <use>, reference the element to render it:

<svg>
  <use xlink:href="#circle" />
</svg>

Since the <svg> containing <symbol> still occupies space on the page, you’ll want to remove it from the layout flow:

<svg style="display: none;">
  <symbol id="circle">
    <circle cx="20" cy="20" r="20" fill="red" />
  </symbol>
</svg>


Please support this site and join our Discord!