Simple sprites
This is the first of three tutorials on sprites. So lets start with the basics. Sprites are a very good way of having hover effects on an image using only CSS and no javascript. It also puts many images into one to reduce the total page size and requests per page. It is best used in image menus.
The premise behind sprites is simple. You have an image containing all of the images and their hover states. You have ’a’ tags for each image you want (keep in mind you can do this with any block element but hovers are usually associated with links). The link is styled to cover the shape of the image you want and the large image is used as a background and positioned inside the link. The background position is then changed on hover to reveal the hover image.
Here is a sprite image. It contains a menu with two links. The image for a simple sprite needs a hover and off state for each image.

Now for the code. We need two links. one for each menu item. I have text within the links for the benefit of SEO. We will deal with the text with CSS.
<li id="nav1"><a href="#" title="Link 1">Link 1
</a></li>
<li id="nav2"><a href="#" title="Link 2">Link 2
</a></li>
#nav { position:relative; overflow:auto; }
#nav li { margin: 0; list-style: none; float:left; width: 100px; height: 30px; padding: 0 10px; }
#nav a, #nav a:link, #nav a:visited { text-decoration: none; border:none; display:block; background:url(images/nav_sprite.gif) no-repeat; width: 100px; height: 30px; line-height: 1px; font-size: 1px; overflow:hidden; text-indent:-999px; }
#nav a:hover { text-decoration: none; }
#nav #nav1 a { background-position: left top; }
#nav #nav1 a:hover { background-position: left bottom; }
#nav #nav2 a { background-position: right top; }
#nav #nav2 a:hover { background-position: right bottom; }
So we have an unordered list with its list items floated left and a width of 100px and height of 30px. we need a display block on the links so that we can give them a width and height. The line-height, font-size and text-indent are to make sure that the text is not seen and does not interfere with the link if the page zoom is changed in the browser. As you can see all links use the same background image so there is only one request and the file size is smaller than for four images. The position of the image is moved to display the different images in a similar way to my previous post: ’CSS Peephole’.
And that is it. Simple and very effective. Here it is in action: