Skip to content

reusing and restyling inline SVG

jackdarker edited this page Apr 23, 2022 · 2 revisions

Now we have our inline SVG and can insert them directly into a page.
But would it be possible to just reference to a already present SVG with <use>? This would be helpful for using icons in text.
Lets assume we have this image inlined as a definiton (notice that its invisible due to the attributes).
<svg height="0px" visibility="collapse">
<circle id="circ" cx="50" cy="50" r="40" stroke-width="4" stroke="green"/>
</svg>

Now we can reference it in other svg-nodes. Notice that the #id needs to be unique.:
<svg width="100" height="100">
<use xlink:href="#circ" style="fill:gray;stroke:black!important;"></use>
</svg>

For an external file we just have to prepend filename:
<svg><use xlink:href="test-ext-svgdefs.svg#icon-pencil"/></svg>

How about styling, f.e. changing the fill-color?
The above example adds some styles to <use>. But that doesnt work as expected:

  • you cannot override styles that are explicitely set in the definition. Different pages tell you otherwise but it doesnt seem to work for me.
    (It didnt matter if you add style="stroke:green;" or stroke="green" to the definition.)
  • you can set styles that are not set in the definition
    Therefore the fill is applied to the svg but not the stroke (even if it is set to !important).
Clone this wiki locally