Inline SVG embedding is great for both web developers and designers. It lets you put scalable vector graphics right into your HTML code. You can easily change the graphics using CSS and JavaScript, making them more flexible and interactive. Plus, inline SVGs don’t need extra HTTP requests, so your pages load faster and work better.
Options for reusing SVG
Let’s say you would like to use the same SVG multiple times.
Unfortunately, inlining it might not be the best option, as you would have to repeat the markup for the whole image each time.
You can use it as <img>
or <object>
or even use the background-image
method. It would instruct your browser to reuse the same image. Each method is great if you don’t want to manipulate your SVG via CSS or JS.
So is there another way? One where you can reuse the image, but style it the same way as inline SVG? Of course, there is.
Reusing inline SVG with <symbol> and <use>
SVG has an element that allows you to define a template object, that can be used multiple times. The best part is it works exactly the same way as inline SVG because… it is one.
We are going to transform a standard SVG into a symbol and use it.
As an example, we’ll use the following SVG:
<svg>
<circle cx="100" cy="100" r="50" stroke="black"
stroke-width="5" fill="red" />
</svg>
The next step is to change it to include a symbol:
<svg style=”display: none”>
<symbol id="symbol">
<circle cx="100" cy="100" r="50" stroke="black"
stroke-width="5" fill="red" />
</symbol>
</svg>
What exactly happened?
First off, we’ve hollowed out the <svg>
tag and set the style to display: none
. Otherwise <symbol>
would not be visible, but SVG would have a height and width, which is not perfect.
We’ve created the <symbol>
tag and assigned an id
to it. If you have any important attributes on a <svg>
tag level move them here. Adding an id is crucial, as it allows SVG to reference this symbol later on.
Now we can use it with a <use>
tag:
<svg>
<use xlink:href='#symbol' />
</svg>
Just like that! Now you can create multiple copies of your symbol, and save on HTML size. Of course, you can use CSS to style linked SVG. If you are curious how it all works just take a look at the following codepen: https://codepen.io/devprogrammer-com/pen/wvEQzQm
In conclusion, reusing inline SVGs is an efficient way to reduce code repetition and maintain flexibility in styling and interactivity. By utilizing the <symbol> and <use> tags, you can create reusable SVG templates without sacrificing the advantages of inline SVG embedding. This method ensures you can deploy multiple instances of the same graphic while keeping your HTML size minimal and manageable. Check out the provided codepen link to see how it all comes together, and start implementing this technique in your projects today!