Warning This article was written over six months ago, and may contain outdated information.

Using SVG for scalable icon sprites isn’t a new idea, but the technique required to use them is (as with all CSS spriting) a little verbose, needing multiple instances of background-position . A feature from SVG 1.1, Fragment Identifier Linking, makes it much easier, and will be available in the forthcoming Firefox 15.

Fragment Identifier Linking involves adding a parameter to the URL of an SVG file, which specifies a region of that file to be displayed. For example, take a look at the file faces.svg, a simple SVG file composed of two faces. If I wanted to link directly to the monkey face, here’s the URL I’d use:

faces.svg#svgView(viewBox(0,0,48,41))

The parameters in viewBox define the region of the file containing the monkey face icon: the x and y co-ordinates of the top left corner, then the width and height.

You can define shortcuts to image regions by adding views into the SVG source. This is done with the view element, which requires at least the viewBox parameters and a unique identifier:

<view id="monkey-view" viewBox="0 0 48 41"/>

Once this view is defined you can link to it using the id as a fragment of the URL :

faces.svg#monkey-view

Whichever way you want to use Fragment Identifiers, once you’ve defined your URL s, you can use them to display sprites in CSS :

E { background-image: url('faces.svg#svgView(viewBox(0,0,48,41))'); } E { background-image: url('faces.svg#monkey-view'); }

It must be noted that this isn’t clipping the background, it’s just linking to a specific region; if you have multiple sprites in an image, it’s possible that they could also be displayed, just as with bitmap sprite sheets.

If you have Firefox 15 or above you can take a look at the demo I’ve put together. The SVG image is shown at the top of the page, then each instance of h1 uses a different syntax to call only part of the same image.

Demo: SVG Fragment Identifier Linking

As far as I’m aware this only currently works in Firefox 15+; I’ve tested in Chrome and Opera and neither supports it, but haven’t checked IE yet . Update, 26 September 2014: Fragment identifiers are fully supported in IE10+, and in Chrome and Safari (7.1) when used in the img element and inline SVG — not as CSS background images.

I first read about SVG Fragment Identifiers on Robert Longson’s blog. The SVG spec has further details (including extra parameters). If you want to know why the use of SVG is a good idea, David Bushell’s article, Resolution Independence With SVG , provides an excellent introduction.

Share this: Twitter

Facebook

