htmlsvg

Display inline SVG in multiple locations


Using HTML5, how can you place inline SVG once then display in multiple locations? I want the SVG code to not display where it is placed, but in multiple locations where it is referenced, without relying on CSS. There is a slightly related question.


Solution

  • You can use the <use> tag to display SVG in multiple locations.

    <body>
        <svg width="0" height="0">
          <defs>
            <rect id="MyRect" width="60" height="10" fill="blue"/>
          </defs>
        </svg>
        <svg width="50" height="50">
          <use x="20" y="10" xlink:href="#MyRect" />
        </svg>
        <svg width="50" height="50">
          <use x="20" y="10" xlink:href="#MyRect" />
        </svg>
    </body>