Fast rollovers, no preload needed

I use another method* than this one to avoid multiple preload images on the page, but this one is neat.
(*I will try in a next post to publish the other method)

When using CSS rollovers with images, two, three, or more images must be loaded (and preloaded for best results) - one imgae for each state (normal, hover, active, visited etc). Putting all pictures into one image makes dynamic changes faster and requires no preload.

Let's have a simple example. The menu items are the a-elements with display:block. Proper padding and background image for a, a:hover and a:active make the rollover. To simplify the rollover, I used one picture containing three states of a button - normal, hover, and active:

rollover background image

Note: There is empty space left under each state-image. I made it to don't bother with wrong box model (it doesn't matter if the button exceeds the height I guess it should have, or not).

Usually, in CSS rollovers, we use background images in this way:

#menu a {
   ...
   background: url("button.gif") top left no-repeat;
   ...
   }
#menu a:hover {
   ...
   background-image: url("button-over.gif");
   ...
   }
#menu a:active {
   ...
   background-image: url("button-active.gif");
   ...
   }
/* etc... */

Using one common picture, we don't need to switch background images. We just change the background-position. The :hover state will use the background image moved several pictures to the top (-39px in the example), the :active state will use bigger shift (-78px).

#menu a {
   ...
   background: url("button.gif") top left no-repeat;
   ...
   }
#menu a:hover {
   ...
   background-position: 0 -39px;
   ...
   }
#menu a:active {
   ...
   background-position: 0 -78px;
   ...
   }

That's it, folks. Just one image is used (no preload is needed), state switching is as fast as possible (moving background position is much faster than replacing background image). AFAIK, it works in every CSS2 capable browser (IE5+, Mozilla, Opera, Safari etc.)

Source: Petr Stanicek

1 Comment

  • Looks good in theory, but you'd have to fix the font size for this to be useful, try using this at 400% font size, you'll see all of the images.



    I suppose that this could be accomodated by making the image much taller, or perhaps placing an opaque div under the text positioned so that the area that the bottom two images take up in the "default" state won't be visible.

Comments have been disabled for this content.