This tutorial describes two ways to create sprites containing many images. However, it uses SVGs rather than the more well-known bitmap techniques.
SVGs are ideal for logos, diagrams, and icons for several reasons:
It’s easy to created and manipulate SVGs on the client or server.
Unlike bitmaps, SVGs can be scaled to any size without losing quality.
Unlike webfont icons, SVGs remain pin-sharp and can apply multiple colors, gradients, and even complex filters.
What are Image Sprites?
Image sprites have been a good-practice technique for many years. If you require a number of regularly used graphics, you place them in a single image rather than individual files. For example:
This example contains eight 24×24 icons in a single 192px × 24px file. The file may offer slightly better compression and it only requires a single HTTP request for all icons to become visible. Loading eight separate icons is unlikely to take much longer over HTTP/2, but the images could appear at different times and would only be cached on first use.
If you wanted to show the right-most printer icon, CSS can display the correct image by positioning the background:
background: url(‘sprite.png’) -168px 0;
Various tools can be used to calculate pixel positions and generate CSS code:
SVG Image Sprites
Multiple SVG images can also be placed into a single SVG file and each can be referenced by an ID rather than a pixel position.
The most common technique is to define individual images within an SVG
A single sprite can be used any number of times throughout a page with SVG
Unfortunately, older browsers such as IE11 and below won’t load the external image. The best workaround is to embed the full SVG into the HTML markup and reference each sprite using its target. For example:
SVG Sprite Stacks
If this SVG is named sprite.svg, you can add a #target-name to the URL to show a specific sprite. For example, the URL sprite.svg#circle displays the layer with the ID of “circle” at any dimensions you choose. It can therefore be used in an :
Or as a CSS background:
Or in an
Or in an
The method works in all browsers including Internet Explorer 9 and above.