Include an SVG with an Image Tag

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 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.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today