SVG Sprites

Just like bitmap images we can create sprites from SVGs. They're not quite the same, but work just as well.

First we'll need to set up our sprite before we can use it on the page.

Start by opening up an SVG in our HTML like so:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">  
    // SVG content will go here
</svg>  

We'll then need access to an SVG. You can do this by opening up your SVG file (This can be created by Illustrator or whatever) with a text editor. You'll see something like this:

<?xml version="1.0" encoding="utf-8"?>  
<!-- Generator: Adobe Illustrator 16.0.4, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->  
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">  
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"  
     width="38px" height="100px" viewBox="0 0 38 38" enable-background="new 0 0 38 38" xml:space="preserve">
<g>  
    <path d="M24.3,21.6c-0.6,0-1.2,0.3-1.6,0.7l-5.9-2.9c0-0.1,0-0.2,0-0.3c0-0.1,0-0.2,0-0.3l5.9-2.9  c0.4,0.4,1,0.7,1.6,0.7c1.2,0,2.2-1,2.2-2.2s-1-2.2-2.2-2.2c-1.2,0-2.2,1-2.2,2.2c0,0.1,0,0.2,0,0.3l-5.9,2.9  c-0.4-0.4-1-0.7-1.6-0.7c-1.2,0-2.2,1-2.2,2.2c0,1.2,1,2.2,2.2,2.2c0.6,0,1.2-0.3,1.6-0.7l5.9,2.9c0,0.1,0,0.2,0,0.3  c0,1.2,1,2.2,2.2,2.2c1.2,0,2.2-1,2.2-2.2C26.5,22.6,25.5,21.6,24.3,21.6z"></path>
</g>  
</svg>  

This is not very readable and we don't need it all. What you'll need is the path element and everything to go with it.

We can add that to our inline SVG we created earlier.

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">  
    <symbol id="icon-share" viewBox="0 0 38 38">
        <title>Share</title>
        <path d="M24.3,21.6c-0.6,0-1.2,0.3-1.6,0.7l-5.9-2.9c0-0.1,0-0.2,0-0.3c0-0.1,0-0.2,0-0.3l5.9-2.9  c0.4,0.4,1,0.7,1.6,0.7c1.2,0,2.2-1,2.2-2.2s-1-2.2-2.2-2.2c-1.2,0-2.2,1-2.2,2.2c0,0.1,0,0.2,0,0.3l-5.9,2.9  c-0.4-0.4-1-0.7-1.6-0.7c-1.2,0-2.2,1-2.2,2.2c0,1.2,1,2.2,2.2,2.2c0.6,0,1.2-0.3,1.6-0.7l5.9,2.9c0,0.1,0,0.2,0,0.3  c0,1.2,1,2.2,2.2,2.2c1.2,0,2.2-1,2.2-2.2C26.5,22.6,25.5,21.6,24.3,21.6z"></path>
      </symbol>
</svg>  

You'll notice we've wrapped our path inside a symbol element. We've also given the symbol element an id so we have something to target it with. We've added a title element for accessibility. The only other thing we copied straight from our SVG file was the viewbox attribute. This is what defines the canvas of our SVG.

To use this on our page we need the following code wherever we'd like our share icon to appear:

<svg class="social share svg">  
  <use xlink:href="#icon-share" />
</svg>  

I've set up the following Codepen demo for you to see it in action.

If you want to read up more on SVG sprites, check out this great article from 24 Ways last Christmas.

Cheers for reading.