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):

Icons are stored in a single image file

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;
}

Leave enough room for icons in the design

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;
}

All displayed icons come from the same image file

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.

  

 

 

 

back to top