Learn how to set an elements background image to embedded SVG. This method has an added benefit of not incurring any HTTP requests, as the SVG is simply embedded into the CSS. They can also 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 using this approach.
If you’re looking for the ability to display icons at different sizes and want to modify the SVG interaction styles (such as on :hover
), this is could be a good option. One negative to adding the interaction styles is that it requires you to duplicate selectors and the SVG markup; the more icons you have, the larger your stylesheets will become.
[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 star. 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 a 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 in-line block because by default in-line 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 the icon star class. I'll add a background image property. In the URL function, I'll add double quotes and I'll start by typing data image SVG plus xml and a comma. Now I'll paste some SVG markup.
[00:58] I'm going to remove some of the extra space. You can see our syntax highlighting is way off, so I need to change every double quote inside of the SVG to a single quote. With those changes, you can see that our background images are now being displayed.
[01:13] In order to make this more cross-browser compatible, we need to encode any special characters such as carats, spaces, equal signs, slashes, colons, etc. What I'm going to do is copy my code and I'm going to paste it into this URL decoder-encoder.
[01:35] This is a just a Web app I found online, but a lot of tech centers just have this feature as well. With my markup pasted, I'll hit encode. Now I've got markup that I can use in my CSS. I'll copy that. I'll just replace previous SVG markup with the encoded SVG. You can see our icons are still being displayed.
[01:57] Next, let's target icon star hover. Set a background image. I'll say data image. Just as before, I'm going to paste an SVG. This time this SVG has a path with a fill of gold color. That'll give us our hover effect. Again, I need to change double quote to a single quote.
[02:29] I'll copy this markup, encode it. I'll grab the encoded copy and replace it. Now on hover, our background images are being swapped. Let's add a transition to make that background image swap smoother. Now on hover, our background images swap with a nice easy transition.
To automate svg escape conversion, with sass, you can use this function: https://codepen.io/jakob-e/pen/doMoML