Adding an SVG with HTML5

When it comes to add an SVG to the page, so display an small icon or a big image, there are different ways to do it with pros and cons:

Using the “object” tag

I believe this to be the most common approach, which just embeds an svg into the page by requesting it as a resource from the server and embedding it into the page as a document. This one allows to simplify the HTML a very lot while keeping all the SVG details.

Example

<object type="image/svg+xml" data="images/logo.svg" id="logo"></object>

Known issue
On being a different document (like using an iframe) your styles won’t reach it. That may not be an issue to you but if you are planning to adapt its size or filling colors contextually or reactively then it can be. To sort it out you have different solutions, from accessing the element on runtime with javascript and override its styles directly to attach a link inside the SVG file that loads the required stylesheet file along the doc. Still, contextual styling can be a problem.

Solution: Link1.

Using the “img” tag

Example

<img type="image/svg+xml" src="images/icons/icon_arrow.svg" alt="Arrow" class="svg-icon svg-icon-arrow" />

Using the “svg” tag

You can actually copypaste the entire SVG into the code, which makes the code dirtier and forces the browser to download it every single time, and also can be much dirtier if the SVG it’s a complex one with many tags in it, but still, you can:

Example

<div>
    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 viewBox="0 0 59.9 60" style="enable-background:new 0 0 59.9 60;" xml:space="preserve">
        <polygon class="st0" points="47.8,30 18.6,0.8 14.4,5 39.4,30 14.4,55.1 18.5,59.2 "/>
    </svg>
</div>

More info

Leave a Reply

Your email address will not be published. Required fields are marked *