How to use CSS sprites

CSS sprites are a combination of images and the proper use of the background-position property. A sprite is an image made up of several other smaller images with a certain distance between each image. Images are disposed in rows and columns along the horizontal and vertical axes, x and y, exactly the same axes used in the background-position property. For example, if you have a sprite like this:

You have five lines with five stars per line. The first thing you need to do is to open an image editor and get the exact dimensions of each star. Let's say that in this case a star is 16 x 16 pixels wide. Now you know that a row is 16 pixels tall, plus an additional vertical space between each row. Again, use your image editor to get this length. Further, since there's also an horizontal space between a star and another, you should calculate even this measure.

Once you got all your data, you can use the background-position property to move along the x and y axes. Remember that the first value of this property represents the x-axis , while the latter is the y-axis. So, to get the latest row of this sprite, you could write the following (assuming that each row is 20 pixels tall):

#sprite {
  width: 100px; /* 20 x 5, adding 4 pixels between each star */
  height: 20px; /* height of a single row, adding 4 pixels between each row */
  background-image: url(sprite.png);
  background-repeat: no-repeat;
  background-position: 0 -100px;
}

A negative value on axes causes the position of the background image to be calculated in the opposite direction. So if you specify a negative value on the y-axis, the background image will be pushed upwards (default is downwards), and if you specify a negative value on the x-axis, the background image will be pushed leftwards (default is rightwards).

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.