Figure 7-4. Mini CSS sprite for menu rollover

Chapter 7 - CSS Optimization

You can use CSS to create simple rollover effects. But for more complex rollovers the classic method is to use two images for each button: one for the “on” state and one for the “off” state. The problem with this method is that it doubles the necessary HTTP requests and can cause flickering problems when the “off” image is not preloaded. A better way is to combine the on and off state images into one mini sprite and switch the background position on rollover (see Figure 7-4):

<style type="text/css">
<!--
a:link, a:visited {
	display: block;
	width: 127px;
 	height:25px;
	line-height: 25px;
	color: #000;
	text-decoration: none;
	background: #fc0 url(image-rolloverdual.png) no-repeat left top;
	text-indent: 25px;
	color: #000;
}
a:hover {
	/* background: #c00; */
	background-position: right top;
	color: #fff;
}
-->
</style></head>
<body>
<p><a href="#">About Us</a></p>

About Us

mini css sprite for dual rollover

Figure 7-4. Mini CSS sprite for menu rollover

The background in the off state (:link) positions the background image to the left and top, showing the off state portion of the image. On rollover (:hover), the background position is shifted to the right, displaying the “on” portion of the background image. The width value effectively clips the image to show only the portion of the image that you want to display. Note that the next section shows a more complex CSS sprite example.

You may want to zero out margin and padding values to eliminate rendering differences between browsers thusly:

a {
    margin:0;
    padding:0;
}

This will zero out all the margins and padding for all links, however. It is better to be specific in your selectors to avoid coding extra CSS:

#nav ul li a {
    margin:0;
    padding:0;
    ....
 }

See the "Use a Reset Stylesheet" section, earlier in this chapter, for more ideas along these lines.