Improve the Speed of Your Site by Using CSS Sprites

Reducing the number of HTTP requests and the bandwidth used is and will continue to be a challenge as designers build ever more elaborate designs. One area where you can both reduce the number of requests and bandwidth is by combining styling images that creep into the design such as corner images, line images, gradients, backgrounds, and so forth. First, start with the basic uses for styling images, as shown in Figure 1.

Figure 1 Box with rounded corners

This simple box is a common use of styling images; however, it is expensive in terms of the number of requests. This example uses eight individual images (one for each corner and each line). Each of these eight images are show in Figure 2.

The yellow background is added to make it easier to searpate images. These images can be combined into a couple CSS sprite images; however, before you get there,you need to start with the CSS and see how it changes to use CSS sprites. Following is an exerpt from the CSS used to create the box in Figure 1.

The first CSS class, Top, is used to draw the line on the top of the box. You should notice that it uses a height parameter and a repeat of repeat-x, causing it to properly space the line for the corners and repeat it across the width of the box. The class TopLeft is used for the upper left corner of the box, and uses a fixed height and width. Although there are other statements in the classes, they are not critical in determing how to combine images. Essentially, you need to separate the images into three categories as identified below.

Fixed height and fixed width

repeat-x (horizontal lines)

repeat-y (vertical lines)

Now that the images have been separated into categories, you can start to combine the individual images into three by using your favorite paint program. The combined images should look similar to the three shown in Figure 3.

Figure 3: Combined images

Now that that the three images are combined, you can start to modify the CSS to use these images. To put these images to use, you use a slightly modified background statement in the CSS as follows:

background: url(image_file.png) -x -y;

The -x and -y parameters are added to the statement to identify the upper-left corner to start the background. Listed below are the four cordinates needed for the corners.

Upper Left: -0 -0

Upper Right: -10 -0

Lower Left: -0 -10

Lower Right: -10 -10

Obviously, one major key to sprite images is determing the proper offsets to use. With this information, you now can modify the original CSS to use these images. Listed below are the replacement classes for the top line and the upper left corner as shown above.