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

Already subscribed? Sign In

Autoplay

    Add an SVG as a Background Image

    Damon BauerDamon Bauer

    Learn how to set an SVG as the background image of an element. Background images can be resized by changing the width and height of the element containing background image, so it’s easy to create multiple sizes of the same icon.

    However, each background image creates an HTTP request, so be aware of your page load speed. With this approach, you are unable to change attributes on the SVG such as fill or stroke.

    If you want the ability to display icons at different sizes and don’t need to change their appearance or their interaction styles (such as on :hover), this could be a good option for you.

    htmlHTML 5
    Code

    Code

    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
    Transcript

    Transcript

    00:00 Let's start by adding an I element to our HTML, by writing I and giving it a class of icon and icon*. Also going to duplicate this, and add a class of icon-small. Since there's no content inside these I elements, we'll need to add a width and height in order for it to take up any space.

    00:22 Let's do that by targeting the icon class, adding a width and a height. We also need to set display to inline-block, because by default inline elements don't respect setting the height. Now, I'll target icon-small, and set its width and height.

    00:40 Now, let's target icon. I'll set its background-image property to the URL of an SVG, and right away you can see those icons are displayed. I'll duplicate the icon CSS, this time I'll add the hover pseudo class, and I'll change the background image to point to a hover version of the icon.

    01:04 The only difference of these SVGs is the fill attributes have different colors. Now, when I hover over there, you'll see that the image is swapped out for the hover version. Since this is just CSS, we can make that background image swap smoother by adding a transition.

    01:21 Let's do that by saying transition:background-image .2s ease, and now I've got a smooth transition between background images.

    Discuss

    Discuss