Recipe 3.24. Using Image Sprites


Problem

You want to save on bandwidth by placing all or most icons onto one image.

Solution

Place the most-often-used images into one master image, making sure that there is plenty of space around each image (see Figure 3-63).

Figure 3-63. Icons are placed into one image


Create enough space for each icon's own space. For this example, one icon will be placed next to a heading (see Figure 3-64):

h2 {  margin: 0;  font-family: Verdana, Arial, Helvetica, sans-serif;  padding: 0 0 0 24px;    font-weight: normal; }

Using id selectors, bring in each icon to the appropriate heading by using background-position property (see Figure 3-65):

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 3-64. Making space in the design for the icons


Figure 3-65. The icons are displayed from one single image


Discussion

In much the same way developers use the same image over and over again to make use of a browser's ability to cache an image, using sprites helps push that idea a bit further. By placing the separate graphic elements onto one image, web developers can reduce the amount of server calls to their machines from a browser. This solution would be more apt for sites receiving medium-to-large amounts of traffic.

See Also

The CSS Sprites article at http://www.alistapart.com/articles/sprites.




CSS Cookbook
CSS Cookbook, 2nd Edition
ISBN: 0596527411
EAN: 2147483647
Year: 2006
Pages: 235

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net