Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Embed SVG Directly In Markup with the “Use” Tag

    Damon BauerDamon Bauer
    htmlHTML 5

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.

    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.

    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.

    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.