XML technologies / CSS / CSS Cookbook / Images / Using sprites to store icons
(Excerpt from “CSS Kochbuch” by Christopher Schmitt)
Problem
You want to save bandwidth by storing all icons in a single image file.
Solution
Store frequently used graphics in a single file, leaving enough space around each image (see the next figure). Otherwise, the icons would partly or completely overlap the heading. In our example, each icon is placed near a heading (see the figure after that):
Figure: Icons are stored in a single image file.
h2 {
margin: 0;
font-family: Verdana, Arial, Helvetica, sans-serif;
padding: 0 0 0 24px;
font-weight: normal;
}Figure: Leave enough room for icons in the design.
Use ID selectors and the property background-position to assign specific icons to headings (see the following figure):
h2#warning {
background-image: url(sprite-source.gif);
background-repeat: no-repeat;
background-position: -16px 24px;
}
h2#questions {
background-image: url(sprite-source.gif);
background-repeat: no-repeat;
background-position: -16px 60px;
}
h2#comment {
background-image: url(sprite-source.gif);
background-repeat: no-repeat;
background-position: -16px 96px;
}
h2#document {
background-image: url(sprite-source.gif);
background-repeat: no-repeat;
background-position: -16px 132px;
}
h2#print {
background-image: url(sprite-source.gif);
background-repeat: no-repeat;
background-position: -16px 168px;
}
h2#search {
background-image: url(sprite-source.gif);
background-repeat: no-repeat;
background-position: -16px 204px;
}Figure: All displayed icons come from the same image file.
Discussion
Some developers reuse the same image throughout a website to take advantage of the browser’s local file cache. Using sprites takes this concept a little further. Storing several individual images in a single file lets developers reduce web server requests. However, this solution is better suited to websites with medium to high traffic.
See also
The article on CSS sprites.
Copyright of the German edition © 2007 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “CSS Kochbuch” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln