Sponsor: The CSS Anthology
The CSS Anthology: 101 Essential Tips, Tricks & Hacks (external link)
Blog Entry
CSS Image Rollovers with One Image
Published on the 13th of May 2008
CSS image rollovers are common amongst web designers because they are easy to setup and they do not require mucking up the HTML. To change the background image on a rollover, one simply has to use the :hover pseudo-class on the target element, changing the background image when the element is hovered over. Note that in IE6 and in previous versions of IE, the :hover pseudo-class only works on anchor (<a>) elements. Anyhow, your code will look something like this:
CSS
div#banner {
background: url('canada.png');
height: 200px;
width: 400px;
}
div#banner:hover {
background: url('manitoba.png');
}
And output something like this:


Overall, a generic CSS image rollover is a breeze. However, one issue can arise with using two separate images, one for the initial state (external link) and one for the rollover state (external link): a delay in loading the rollover image. There is a small delay in loading the rollover image because it is not pre-loaded by the browser before the user hovers over the element. Rather, the image is loaded when the :hover state is activated for the element. Now, the image can be pre-loaded using a number of methods, including JavaScript, but it is much easier to achieve using CSS itself.
CSS offers the nifty ability not only to control the background image of an element, but to control that image's position within the element (external link) as well. So, rather than changing the background element on a rollover, one can just change the position of the current background image instead. By combining the two different background images into one image file (external link) and then changing the position of that image based on the element's state, the small delay is entirely avoided. The styling is not very complex either:
CSS
div#banner {
background: url('canada_manitoba.png');
height: 200px;
width: 400px;
}
div#banner:hover {
background-position: 0px -200px;
}
And the output is exactly the same, but without the delay! Make sure to set the proper position for that specific element and to that specific image. See, using one image for CSS rollovers is pretty easy and it avoids that inconvenient loading delay.
Sponsor: Songbird Media Player
Desktop web player, a digital jukebox, and web browser mash-up. (external link)

