Chris Coyier posted an article on CSS-tricks about using SVG sprites and the <use> tag to replace icon fonts.

I am a big fan of SVG, and I actually used the same technique for slides of a recent conference I talked at to build slides with consistent assets. I defined my base shapes in a SVG with only <defs> in the <head> of the slideshow and then reused them in all schemas with no copy paste. Making a change to a shape is reflected at everyplace it is used with zero change.

For example there is one definition for a smartphone and it is reused multiple times:

<html lang="en-US">
  <head>
    <!-- snip -->
    <svg viewBox="0 0 400 200" style="height: 0; width: 0;">
      <defs>
        <!-- 25x40 centered phone -->
        <g id="phone">
          <path class="device" d="M -12.5 -20 L 12.5 -20 L 12.5 20 L -12.5 20 Z" />
          <path class="device" d="M -3 -17 L 3 -17" />
          <path class="device" d="M -12.5 -14 L 12.5 -14" />
          <path class="device" d="M -12.5 14 L 12.5 14" />
          <circle class="device" cy="17" r="1.5" />
        </g>
        <!-- snip -->
      </defs>
    </svg>
  </head>
  <body>
    <!-- snip -->
  </body>
</html>

Since I was also scaling and rotating the assets, I made sure my shapes were defined around their center. Placing them on the final schema was then done using transform="translate(x y)" where x and y were the my target center, whatever scaling was. And rotation occurred around their centers too. In order to easily spot target scaling, I put a comment on their expected size, it also allows to modify the shape with more confidence it won’t break any slide.

Using them is thus:

<svg viewBox="0 0 400 200" class="someSchema">
  <style type="text/css" ><![CDATA[
    .someSchema .device {
      stroke: purple;
      fill: #222288;
      stroke-width: 1.5;
    }
  ]]></style>
  <use xlink:href="#phone" class="device" transform="translate(360, 90)" />
  <!-- snip -->
</svg>

In order to style them, I attached a class attribute to all of my schemas and put some CSS inside the SVG itself, all rules prefixed by the class not to leak outside. My shapes were defined with a few classes too to allow inner styling. Chris Coyier mentions browsers use shadow dom to scope styles, this seems to be the case on Chrome but I found Firefox to react much differently.

Passed the struggle to get styles working, in the end it was very productive to work that way. My will to do so mostly comes from software development mojo Don’t Repeat Yourself. Did I find a cross browser solution for styles faster, maybe shapes would be a bit more well looking!