I'm trying to create an external file having the SVG icons in below format
<svg>
<symbol id="icon1" viewbox="0 0 16 16">
<path>....
</symbol>
<symbol id="icon2" viewbox="0 0 16 16">
<path>....
</symbol>
</svg>
And is there a way possible to link the above file to the HTML so that I can use the icon with below code
<svg>
<use xlink:href="#icon1" />
</svg>
<svg>
<use xlink:href="#icon2" />
</svg>
I creating a flask web app for a practice where I only need 5-6 icons. Currently, I'm using inline SVG which is working fine but it makes the code very large and I'm looking for a way to refactor the code.
CodePudding user response:
You can use SVG Sprites to refer to.
You would have one SVG-File like this:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<symbol id="icon1" viewBox="0 0 34 73">
// Your SVG paths and so on
</symbol>
<symbol id="icon2" viewBox="0 0 34 73">
// Your SVG paths and so on
</symbol>
and you use the single icons from that file like this in your html:
<svg class="your-class-to-style">
<use xlink:href="{svg-path}/#icon1"></use>
</svg>
<svg class="your-class-to-style">
<use xlink:href="{svg-path}/#icon2"></use>
</svg>
CodePudding user response:
You can use the filename in front of the id reference. Like here I'm referring to the symbol s2
in the file symbols.svg
. This needs to run from a webserver.
<!DOCTYPE html>
<html>
<head>
<title>SVG symbol</title>
</head>
<body>
<h1>Test</h1>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<use href="symbols.svg#s2" />
</svg>
</body>
</html>