Icon_search

Flickerless CSS Image Rollovers with no JavaScript

Posted on 04/23/2009 by Travis
 | 

Using an image as a background lets you have a lot more control over certain elements (like anchors). One of the main problems with images as backgrounds for anchors, however, is when you have a separate image as the rollover state. When the anchor is hovered over, you can see a brief blink while the rollover image is loaded for the first time. Of course, you can use a JavaScript pre-loader, but this seems like too much trouble to me. This post will show you how to combine the two images so they get loaded once, at the same time, when the page loads.

As a side note, you should check out my post on Better Text Replacement with CSS to get an idea of how to properly replace elements with background images.

First off, let's say we want to replace the logo link in our header with a standard logo and a rollover logo. Here are our two images (I'm using the logo from my blog):

initial logo state
rollover logo state

Our HTML code might look like this:

And, our CSS code would look like this:

It's a simple empty anchor that is display:block; and has the first image as the background, then another background image for the rollover. The second image won't load when the page loads. It loads the first time it's requested; when you hover over the logo. This will cause a very brief flicker while the image is loaded.

The solution to this problem is insanely simple. All we need to do it combine the two images into one, then just re-position the background image when we hover over the anchor. Here is our new combined image:

combined logo image

Our HTML stays the same, but our CSS changes slightly:

Since each of our separate logo images were 81px tall, we just combine them to make an image that is 162px tall. Our CSS will only show the top 81px of the image initially, then will shift the image up by 81px to show the rollover state.

Tagged:  css, xhtml, background image