Add an SVG as a Background Image

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

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.

[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.

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