Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to do a CSS rollover?

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?

like image 211
Jason Z Avatar asked Oct 06 '08 17:10

Jason Z


People also ask

What is a CSS rollover?

Sometimes, a rollover is used to allow users to compare two versions of a similar image. If a CSS rollover is being used to compare two images, then a text description must be included. In the example below, a CSS rollover in an empty link text is used to compare a color and black and white version of a bar chart.

How do I create a rollover effect in CSS?

By making the link a block element and giving it a background image, we can turn the link into a button. We then simply jiggle the background image around to create the rollover effect.


1 Answers

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)

like image 194
Dan Avatar answered Sep 19 '22 14:09

Dan