Creating Bulletproof SVG Icons

by Andrey Kuzmin, @unsoundscapes

Creating Bulletproof
SVG Icons

Andrey Kuzmin, @unsoundscapes

Zalando

What do we want from a spriting method?

  1. Performance: payload, amount of requests, CPU usage

What methods to consider?

PNG SVG

CSS Sprites

css sprite

CSS Sprites

css sprite
      .icon {
        background-image: url(icons.png);
        display: inline-block;
      }
      .icon-twitter {
        background-position: -137px -50px;
        width: 31px; height: 31px;
      }
    

CSS Sprites drawbacks

CSS with Data URIs

CSS with Data URIs

      .icon-close {
        background-image: url('data:image/png;base64,iVBORw0K...
      }
    

Icon Fonts

      @font-face { font-family: IconFont; ... }
      .icon:before { font-family: IconFont; }
      .icon-close:before { content: "\025B6"; }
    

SVG fragment identifiers

      <svg>
        <view id='icon-close' viewBox='0 40 20 20'/>
        ...
      </svg>
      <img src='icons.svg#icon-close' alt='x'>
    

Combined SVG with symbol tags

      <svg>
        <symbol id="icon-close" viewBox="0 0 20 20"/>...</symbol>
        <symbol id="icon-menu" viewBox="0 0 20 20"/>...</symbol>
        ...
      </svg>
      ...
      <svg><use xlink:href="#icon-close"></svg>
    
SVG Superman

Illustration by @01k

Combined SVG Advantages

Combined SVG Gotchas

      var xhr = new XMLHttpRequest();
      
      
    

What about the tooling support?

gulp-svgstore

      var gulp = require('gulp');
      var svgstore = require('gulp-svgstore');
      gulp.task('svgstore', function () {
          return gulp.src('src/icons/*.svg')
              .pipe(svgstore())
              .pipe(gulp.dest('dest/img'));
      });
    

gulp-svgstore

What about the fallback?

CSS Sprites

Fallback Parachute

Illustration by @01k

CSS Sprites as a fallback

HTML

      <span class="icon icon-close">
        <svg width="50" height="50">
          <use xlink:href="#icon-close"></use>
        </svg>
      </span>
    

CSS

      .icon { display: inline-block; vertical-align: middle; }
      .icon > svg {
        display: block;
        fill: currentColor;
        pointer-events: none;
      }
      .no-js .icon > svg { display: none; }
    

Recap

SVG Superman

Zalando

Questions?

Andrey Kuzmin, @unsoundscapes

Links