SVG Icon Methods

There are many different ways of packaging up vector assets in SVG. So many, in fact, that it’s becoming a bit difficult to keep track of them all. I figured I would roll a bunch of the more popular ones up here as a handy reference.

We will be using some lovely bunny artwork by Brad Ashburn.

Inline vs Linked SVG

One of the most direct ways of using SVG is to drop it right into your HTML document. This inline SVG format allows you to script and style between the HTML and SVG document. When working with complex graphics, it is generally convenient to package them into external resources and link to them, as the SVG markup can get quite long. Most of these methods will focus on linked (external) icon packaging techniques.

Inline SVG Example

<!doctype html> <html> <svg><path d="…" /></svg> </html>

<img src=”happy-bunny.svg” <img src="happy-bunny.svg">

Internet Explorer Chrome Firefox Safari Opera iOS Android
9 37 32 7 24 8 4.4

The Original SVG Sprite Sheet

This is the original SVG image, 300 units wide by 100 units tall.

With a Custom View Box

You can set a custom view box on an svg by adding a custom view box fragment identifier to the end of the SVG URL. It would look something like this:

<img src='bunnies.svg#svgView(viewBox(0,0,100,100))'>

Note: You will need to explicitly size the image, as some browsers (CR, S) will not clip to the custom view box.

With a Custom View

You can also target a predefined view element that encapsulates this information. In your SVG you would drop:

<view id='carrot-bunny' viewBox='0 0 100 100' />

Which can then be used in HTML like so:

<img src='bunnies.svg#carrot-bunny'>

Browser Support

9 32 38 7.1 25 8 4.4

Browser support should roughly map to support for SVG fragment identifiers. FF, CR, O versions were only tested for the current release. IE 9 worked, though support is only listed on caniuse as 10 and up. Support is new for the Safari 7.1/iOS 8 release.

Notes & Credits

SVG sprite sheets are similar to icon stacks. What I like about this method is that it works in current versions of Safari (there is a bug with icon stacks), and all artwork is visible in the original image. You do have to do some offset math though.

Icons are public domain from Brad Ashburn over on the Noun Project. Inspired by the comments on a WebKit bug about fragment identifier support.