O'Reilly logo

CSS Cookbook by Christopher Schmitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required