O'Reilly logo

CSS Cookbook, 3rd Edition 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

Using Pseudo-Classes

Problem

You want to add styles to items that are not (typically) based on elements’ names, attributes, or content.

Solution

Create a pseudo-class. Here is an example of a pseudo-class that creates a common rollover effect on HTML links:

a:link {
 color: blue;
a:visited {
 color: purple;
}
a:hover {
 color: red;
}
a:active {
 color: gray;
}

Discussion

In this use of a pseudo-class, a basic link appears in blue. As soon as the mouse pointer hovers over the link, the link changes to red. While the link is being clicked, the link appears gray. When returning to the page with the link after visiting, the link appears purple.

Three other CSS2 pseudo-classes include :first-child (which selects the first child element), :focus (see Removing Dotted Lines When Clicking on a Link in Internet Explorer), and :lang(n).

CSS3 pseudo-classes

The CSS3 specification introduces a new slate of pseudo-classes. Although Internet Explorer does not support these new selectors, browser support is growing for them, as shown in Table 2-2.

Table 2-2. Browser support for CSS3 pseudo-classes

Selector

Firefox 2

Firefox 3.5

Opera 9

Opera 10

Safari 3.1

Safari 4

Chrome

:target

Y

Y

Y

Y

Y

Y

Y

:enabled

Y

Y

Y

Y

Y

Y

Y

:disabled

Y

Y

Y

Y

Y

Y

Y

:checked

Y

Y

Y

Y

Y

Y

Y

:default

 

Y

Y

Y

   

:valid

Y

Y

Y

Y

   

:invalid

Y

Y

Y

Y

   

:in-range

Y

Y

Y

Y

   

:out-of-range

Y

Y

Y

Y

   

:required

  

Y

Y

   

:root

Y

Y

Y

Y

Y

Y

Y

:not()

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