Reputation: 5844
I have an SVG file freshly exported from Figma.
<img src="...">
because I need to style its parts.So, I tried to include it like this:
<svg>
<use xlink:href="http://example.com/myshape.svg"></use>
</svg>
But it doesn't work. MDN states:
The
<use>
element takes nodes from within the SVG document, and duplicates them somewhere else.
It takes nodes from the document. With SVG sprites, you have <symbol>
tags with id
attributes and you reference them with <use>
by adding xlink:href="mysprite.svg#symbolid"
. However, here I need to use the whole document, I.E. the root node. Is there a way to do that?
It would also be great if I don't have to edit the source SVG file, as it's uploaded via an admin panel by the user. It's just a file exported from any vector graphics program.
Upvotes: 10
Views: 9286
Reputation: 24522
For now (as of 2023/11) you need to add an #id to the root of your target SVG and refer it as a "fragment identifier":
<!-- my-vector.svg -->
<svg id="icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<circle r="10" cx="12" cy="12" />
</svg>
<use href="my-vector.svg#icon"></use>
SVG 2 (when implemented in browsers) will allow to reference another SVG file without any fragment identifier:
New in SVG 2: An
href
without a fragment allows an entire SVG document to be referenced without having to ensure that it has an ID on its root element.
Future (there will be no need to define id="..."
on the svg
):
<!-- my-vector.svg -->
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<circle r="10" cx="12" cy="12" />
</svg>
<use href="my-vector.svg"></use>
SVG 2 seems to be in the process of development in major browsers (see this Chrome feature and specifically this Chromium issue: Issue 366545: [SVG2] Allow to reference entire files).
Upvotes: 10