simurai avatar

simurai

UI Designer and CSS Doodler

SVG Stacks

Image sprites are wildly used for downloading lots of icons or UI elements all at once with just a single HTTP-Request. But they are somewhat cumbersome to use because you have to calculate the background-position offsets. You can’t easily add, remove or reorder them without recalculating. Or change the size without a neighbour peeking in from the side.

How could it be solved? Well, by stacking them all on top of each other, turn off their visibility and only show the one you want. Have been wishing this would be possible for a while.. and then this happened (read from below):

Tweets

Oh, nice! The demo already works in Firefox. That’s great news.

There are alternatives to SVG Stacks with better browser support by using embed, iframe, object or img elements, but I still prefer background images because of their easier positioning/resizing. So let’s hope more browsers will also add support for that.

So how does it work? It’s actually pretty simple. Have a look at the source of Erik’s SVG file.

SVG Stacks info graphic

First we give each of our icons in the SVG file a unique ID and the same class name, add some CSS to hide all icons and only display the one that gets selected with :target. And now we can use a hash in the URL to pass the ID into the SVG file, like background: url(icon.svg#ID).

Big thanks to @erikdahlstrom for that technique.

Update: A couple bugs have been added to other browsers so you can track its progress. Opera: “CORE-37596” (no public link). WebKit’s Bugzilla : 91790, 89983, 89985. And please star it in Chromium Issue 128055.

Update II: Michael Schieben created a tool to that turns a folder of SVG files into a single SVG Stack: SVG Stacker

Update III: Looks like “SVG Stacks” got shot down by the WG. But there is still some hope left and it’s probably still in flux. So instead of url() we could use image().

Update IV (Feb 2014): And back alive! Work has started to also add SVG fragment identifiers to WebKit, see this bug. Not sure where that leaves Chrome as they now have Blink.

Update V (Sept 2014): Support is getting a lot better.

One thing that still doesn’t seem to work, and probably never will, is using a SVG fragment identifier as background-image. I’m kinda sad about that since I love to use icons as backgrounds. I heard it’s a security related reason.

Edit this page, leave feedback or send a Tweet.