We regularly use SVG stacks at Magnitude, as they are such a small file size, yet allow for so much customisation without using multiple imagery.

We tested a variety of ways to output our vectors on a page and yet only recently have I come across using Symbols.

One of the bugbears with using SVGs are tackling the viewbox when describing the container/aspect ratio. Symbols allow you to define the viewBox directly on the <symbol> and then not need one when you <use> it later in an SVG. Perfect.

For Example

Instead of using <g> to wrap all of the shapes/paths within the svg, you are able to wrap it all in a <symbol>, as well as embed <title> and <desc> tags, meaning you can ensure accessibility.

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id=“magnitude” viewBox="214.7 0 182.6 792">
    <title>Our nice SEO title!</title>
    <desc>Description too!</desc>
    <!-- <path> -->
</symbol>
</svg>
<svg class="icon">
    <use xlink:href="#magnitude" />
</svg>

Why use Symbols?

  1. The viewBox can be defined on the symbol, so less error prone!
  2. Ensure accessibility by adding title and desc tags within the symbol
  3. Symbols don't display as you define them, so no need for a <defs> block

Helpers

If you have SVG’s which you wish to change to symbols, the amazing guys over at herokuapp (who created the incredible css2sass) have developed a converter, which is extremely simple to use. Just add in your SVG coding and click to convert.

Or, if you’re a fan of using Gulp, there’s a package over on npmjs.com which allows you to converts a bunch of SVG files to a single SVG file containing each one as a symbol.

// To install the package through CLI
npm install --save-dev gulp-svg-symbols
// To run the package in JS with Gulp
var gulp = require('gulp');
var svgSymbols = require('gulp-svg-symbols');
gulp.task('sprites', function () {
return gulp.src('assets/svg/*.svg')
    .pipe(svgSymbols())
    .pipe(gulp.dest('assets'));
});
// To use it on your site:
<svg role="img" class="github">
   <use xlink:href="#github"></use>
</svg>

For more information on SVG symbols, you can read more about them here.

0
Create the perfect Christmas wishlist and hide what people buy you 🙈