DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 3.5 Creating Rollovers Without JavaScript

Problem

You want to create a simple rollover effect without using JavaScript to swap images.

Solution

Use the :hover and :active pseudo-classes to create the rollover:

a:link {
 color: #777; 
 text-decoration: none;
}
a:visited {
 color: #333;
 text-decoration: none;
}
a:link:hover, a:visited:hover {
 color: #777;
 background-color: #ccc;
}
a:link:active, a:visited:active {
 color: #ccc;
 background-color: #ccc;
}

Discussion

The :hover pseudo-class mimics the common JavaScript event onmouseover. Instead of executing a function in JavaScript, when a user rolls over a link with :hover, a different set of styles is applied to the link.

With the selectors having the same specificity, selectors written out of order may stop one of the other styles from appearing. Avoid this common problem by listing the selectors in the order: link, visited, hover, and active. The mnemonic device commonly used to remember the order is "LoVe/HAte."

Although :hover and :active can be applied to any element, they are commonly used on links. Note that browser support for :hover and :active is nonexistent in Netscape Navigator 4. Also, Opera 4 doesn't support :hover.

In the Solution, the two pseudo-classes make sure that the rollover effects occur only on anchor links. Without :hover and :active, modern browsers could legally apply the rollover effects on any anchor elements, as shown in this code and in Figure 3-4:

<h2><a name="europan">Li Europan lingues</a></h2>

Figure 3-4. An unwanted rollover effect on a heading
figs/csscb_0304.gif


See Also

The CSS 2.1 specification for :active and :hover at http://www.w3.org/TR/CSS21/selector.html#x36; an explanation about links and specificity at http://www.meyerweb.com/eric/css/link-specificity.html.

    Previous Section  < Day Day Up >  Next Section