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 duplicatedx— top-left x coordinate to place the duplicated elementy— top-left y coordinate to place the duplicated elementwidth— 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.)
x— x coordinate of the symboly— y coordinate of the symbolwidth— width of the symbolheight— height of the symbolviewBox— 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 theviewBoxdoes not match the givenwidthandheight, e.g.xMidYMid meet(seepreserveAspectRatio)refX— defines the x coordinate of the symbol (which is defined by the cumulative effect of thexattribute, 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 theyattribute, 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
- <use> (MDN) — https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use
- <symbol> (MDN) — https://developer.mozilla.org/en-US/docs/Web/SVG/Element/symbol
- refX » symbol (MDN) — https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/refX#symbol