3.10. Creating Image-Based Rollovers

Problem

You want image-based rollovers to replace text links.

Solution

First, wrap the text inside the anchor element in a span:

<a href="/" id="linkhome"><span>Homepage</span></a>

Next, instead of JavaScript, use the background-image property within the pseudo-class selectors :hover and :active to swap the images (see Figure 3-17):

a span {
 display: none;
}
a:link { 
 display: block;
 width: 125px;
 height: 30px;
 background-image: url(btn.gif);
 background-repeat: no-repeat;
 background-position: top left;
}
a:link:hover { 
 display: block;
 width: 125px;
 height: 30px;
 background-image: url(btn_roll.gif);
 background-repeat: no-repeat;
 background-position: top left;
}
a:link:active { 
 display: block;
 width: 125px;
 height: 30px;
 background-image: url(btn_on.gif);
 background-repeat: no-repeat;
 background-position: top left;
}
The link with default, rollover, and active states

Figure 3-17. The link with default, rollover, and active states

Discussion

Replacing text with an image has five benefits. First, it separates the text from the presentation. The image that contains more elaborately formatted type is part of the presentation and therefore controlled by a style, while the content in the markup remains pure text. The second benefit is that an image heading can be modified across a whole site by one change of the style sheet. The third benefit is that this method works for alternative styles and style sheet switching. ...

Get CSS Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.