Notes

SVG Sprites

Edit on GitHub

Web Development
2 minutes
  • <symbol> allows you to embed the SVG code as well as have it’s own viewBox attribute
  • Elements defined inside the <symbol> element can only be rendered to the browser when referenced by the <use> element.
  • Each symbol will have it’s own id which we will use to reference it
  • Each symbol will have it’s own viewBox property too. The first two values will almost always be “0 0”, the second two will be equal to the size of the icon you have exported
  • You can also use viewBox in <use> instead of sprites. Add that to media queries and you can display only symbol instead a full logo without an extra sprite for that.
  • <symbol> is a better wrapper as compared to <g>. Because a) you can define the viewBox directly on the <symbol> and then not need one when you <use> it later in an <svg>, and b) <symbol> can have it’s own <title> and <desc> tags.
  • <symbol> will have an id for your icon and have all the <path> values

creating a sprite

 1<svg style="display:none;"> <!-- hide it by default so it doesn't render empty space -->
 2  
 3  <!-- Icons go here, each icon will be warpped as a `symbol` -->
 4  
 5  <symbol id="aircraft" viewBox="0 0 62 51">
 6    <path fill="#000000" d="M38.9872..."></path>
 7  </symbol>
 8  
 9  <symbol id="brush" viewBox="0 0 62 62">
10    <path fill="#000000" d="M7.8416..."></path>
11  </symbol>
12    
13</svg>

referncing an icon

1<svg>
2  <use xlink:href="#aircraft"></use>
3<svg>

referencing an icon from an external svg file

you can use the svg’s from an external svg sprite as well by prefixing the identifier by the path to the file something like this:

1<svg>
2  <use xlink:href="path/to/icons.svg#aircraft"></use>
3</svg>

use the same <path> in different sizes

You can use the same path in different sizes and control the sizes by CSS. Just be careful when setting the viewPort attributes within your SVG file.

1<svg>
2	<title>small icon</title>
3	<use class="small" xlink:href="#aircraft"></use>
4</svg>
5<svg>
6	<title>big icon</title>
7	<use class="big" xlink:href="#aircraft"></use>
8</svg>
1.small { width: /*small size*/ }
2.big { width: /*big size*/ }