Inline SVG with the ‘use’ element
Comparing the techniques
SVG sprite — the old technique
Pros
- Single file downloaded by the browser
- PNG fallback easily produced via build-tools (for IE8 support)
Cons
- Tricky to resize
- Cannot re-colour easily
- Cannot fully utilise CSS for styling
- Uses CSS backgrounds, so needs CSS with positional mapping
Inline SVG — the new and improved technique
Pros
- Single file downloaded by the browser
- Can be transformed with CSS – colour, transitions, opacity, etc.
- More semantic; it’s just a reference to an external SVG file and a hash
- No need for any separate CSS
Cons
- IE8 still requires a PNG fallback
- Need to strip ‘fill’ attributes from elements to allow css styling
Using inline SVGs
The outcome of this technique is that you can use the following markup in places
where you may of perviously had <span>
or <i>
elements. The trick here
is the xlink:href
attribute that points to an external file, with a hash
which is the ID of an icon contained within that file.
<svg><use xlink:href="/svg/icons.svg#svg-sync"></use></svg>
Generating the SVG
This is achieved by stripping the original external wrappers from each of your SVG files, then, taking the <g>
, <path>
and other elements that make up the SVG and reconstructing a new file in the following format: (where each symbol
element is a wrapper for the individual files)
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: none">
<symbol id="svg-sync" viewBox="0 0 64 64">
<!-- g's and paths etc -->
</symbol>
<symbol id="svg-trash" viewBox="0 0 64 64">
<!-- g's and paths etc -->
</symbol>
</svg>
You could do this bit manually, but we have tooling in place to handle it for us at JH; check out gulp-svg-sprite and look at the ‘shape’ option for an example. We use that plugin along with a further step to remove any fill attributes (but you can just ensure they are not added by your editor instead).
Styling with CSS
Once you have the newly constructed SVG file in the format shown above, you are ready to start using the icons in your project. With this technique, you can now use CSS properties to control the size, colour, opacity and transitions of the SVG as you would normally have done with a @font-face icon. What is perhaps the coolest aspect of this technique is the ability to instruct the SVG’s fill property to match the colour of its parent element. This means if you have a button with colour: #c8c8c8
, the SVG’s fill property will now also be #c8c8c8
.
Demo
All of this is easier to understand when you can see it actually working, so please check out the following demo to see how we’ve referenced individual SVGs, but applied styles to their parent elements which they then inherit. Note: we’ve put the whole SVG file into the demo HTML for convenience of not hosting it externally.