Include an SVG with an Image Tag

Damon Bauer
InstructorDamon Bauer

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

Since an SVG is really just an image, it can be included on a page just like any other image, using an img tag. This is simple to implement, easy to resize and has the benefit of being cacheable.

There are a couple downsides to this approach, however. You can’t modify the SVG attributes such as fill or stroke; once the icon is included, there isn’t much you can do to change its appearance. Also, each icon you include creates an HTTP request, potentially impacting page load speed.

If you’re looking for an easy way to implement just a couple of icons that don’t need to change, this is a viable option.

[00:00] We'll start out by adding an image tag and provide it a path to an svg, and add a class of icon. This svg that we're linking to doesn't have a width or height attribute. It automatically scales to fill its container, in this case, the body element.

[00:16] We'll go ahead and duplicate this image, and I'll add another one. This time, I'm going to add an icon-small class and an icon-large class. Because we're just using an image tag, we can resize the svg by targeting the class of icon and adding a width, and let's say, of two em and a height of two em. Now, any images, as you can see, with the icon class will be resized.

[00:46] With this approach, we can set up a few different sizes using our class modifiers. Let's target icon-small, give it a width of one em and height one em. I'll do the same for icon-large and change its width and height to three em.