Fast rollovers, no preload needed
(*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:
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