Go Back to Dynamic Site Solutions :: CSS

CSS Background Image Switching

This is a demonstration of combining two CSS techniques — Image Replacement and "Fast Rollovers Without Preload".

The Third Version

This version uses the Gilder/Levin Method of CSS Image Replacement which uses an empty span element. I prefer to use it instead of other image replacement techniques because it's the method that's still usable with the images disabled and CSS enabled scenario, which to me is more important than the empty span elements. This works in IE5+/Win, Firefox, Netscape 6+, Opera 7+, Konqueror 3, Safari, and IE5/Mac.

The Second Version

These background images are twice as tall as the elements that they are applied to. In this version the same background-image is applied to the link and to its corresponding list-item, except the list item has an offset background-position, when one is moused over the link's background turns tranparent so you can see the alternate version that is applied to the list-item and normally is concealed by the link's background. The primary reason for this is to avoid IE6's flickering background image bug. In this version you don't have to have all states for each link in one image, you could use one image for each state, since they are all applied to an element when the document is loaded. This works in IE5+/Win, Netscape 6+, Firefox, Opera 7+, Konqueror 3, Safari, and IE5/Mac.

The First Version

These background images are twice as tall as the elements that they are applied to. So when they are moused over they change position and you see the alternate version without having a second set of images. When a CSS background image isn't applied to an element when the page loads it won't be downloaded until it is needed, thus why changing the background's position is a better method than putting the second background image on a:hover or li:hover. This works in IE5+/Win, Netscape 6+, Firefox, Opera 7+, Konqueror 3, Safari, and IE5/Mac. This method falls victim to the IE6 background-image flicker bug.

Here's the code that does it:

ul#example1 li a {
  background-position: 0 0;
}
ul#example1 li a:hover {
  background-position: 0 -28px;
/* the second number should be the negative height of the link. */
}
#link1 {
  background-image: url(link1_bg_switch.gif);
}

Related Links:

Last update: 2007-02-20