Nharox – Front - End Web Developer

How to create and use a cross-browser SVG sprite

My first tutorial ever! A short and simple tutorial about how to create and use SVG sprites in your web project. Making the switch from icon fonts to SVGs can be a little daunting in the beginning but once you get the hang of it you'll see that it's just much much better. Great performance, good browser support and it ensures a high level of maintainability. You can simply add new icons without big hassles. CSS-Tricks has a few good comparisons.

I know that there are tools available to automatically create a sprite, but I'm going to create one by myself step by step to show how it actually comes together.

Get some icons!

Start up Illustrator and create your own icons or get icons from a site like IcoMoon. Click on the IcoMoon App button in the top right corner and go wild! Once you're happy with your choice, click on the Generate SVG & more button in the bottom left corner and download your icon set on the next page. Grab the SVG folder inside the downloaded .zip.

SVG in HTML

Before we can use our icons though, we have to ensure that it'll work in every browser. The JavaScript plugin svg4everybody will allow us to make external SVG sprites work in every browser. After adding the script, we can add our icons with:

<svg><usexlink:href="assets/svg/sprite.svg#home"></use><svg>

Note that this won't work local and only on a server. The href points to the sprite you want to use and the hash points to the symbol you want to display. You can now style the SVG with ease in your CSS.

SVG in CSS as background-image

This one's a little bit trickier. To make this less of a headache, I'm using a Sass mixin to easily add the icon as background-image:

Quick and easy. This will calculate the y coordinate for the background-position depending on the amount of icons in your sprite. The only thing you have to adjust is the variable. The first number in the brackets is the amount of icons in your sprite.

The only downside to this is that you can't change the colour of your icon with CSS. Depending on the project, I usually have a sprite called bg.svg for icons only used as background-image. In the sprite I change the colour by giving the path a fill="#fff" for example (paths are black by default).