What is the preferred way to do a CSS rollover?

css, html, javascript

Solution

CSS is fine for rollovers. They're implemented basically using the `:hover` pseudo-selector. Here's a really simple implementation:

a{
    background-image: url(non-hovered-state.png);
}
a:hover{
    background-image: url(hovered-state.png);
}

There are a few things you need to be aware of though:

- IE6 only supports `:hover` on `<a>` tags

- Images specified in CSS but not used on the page won't be loaded immediately (meaning the rollover state can take a second to appear first time)

The `<a>`-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called CSS Sprites that can prevent this problem, you can find an example of the technique in use to make no-preload rollovers.

It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using `background-position` so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)):

a{
    background-image: url(rollover-sprites.png);
    background-position: 0 0; /* Added for clarity */
    height: 20px;
}
a:hover{
    background-position: 0 -20px; /* move the image up 20px to show the hovered state below */
}

Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support `background-position`)

Problem

When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?

Original source