Embed SVG Directly In Markup with the “Use” Tag

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

In this lesson, we’ll learn how to embed an SVG sprite into markup and reference it throughout the page using the SVG “use” tag and fragment identifiers.

This has become the standard way of displaying SVG icons because of the ability to dynamically style individual parts (especially interaction states). Also, because the SVG is just markup embedded on the page, it creates no extra HTTP requests. However, the block of SVG needs repeating on every page where icons are used.

[00:00] I'll start by pasting a sprite of SVG symbols directly into the HTML. This is our SVG tag. Each icon is wrapped in a symbol tag that has a unique ID on it. The benefit to symbol elements is that you can add title and description tags for additional accessibility.

[00:20] On the outer SVG tag, I want to set style to Display None so that this block of SVG symbols is not displayed, and it doesn't take up any space. I'm going to collapse this SVG tag. Below it, I'll add another SVG tag, and I'll give it a class of Icon.

[00:41] Inside I'll add a use tag along with an xlink href attribute. I'll provide a value of #plug, which, if I open up the SVG again, you'll recall that this first symbol has an ID of Plug. That's what we are rendering when we say use xlink #plug. The process is the same to add other icons, so I'll just duplicate that code. I'll change plug to star, and I can change it again to umbrella.

[01:17] I'll duplicate umbrella again. This time, I'll add a class to the SVG of Iconsmall. These icons don't have a width and height on their SVG tag, so they'll try to take up as much space as they can. To fix that, let's use CSS and target the icon class. I'll set a width and a height for em, and I'll target Iconsmall and set its width and height to two em.

egghead
egghead
~ 34 minutes 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