Pseudo Classes

News Feed

Pseudo Classes

There is one final group of selectors that is important you have as part of your toolbox. They are the pseudo classes & elements. There are 29 pseudo classes and 9 pseudo elements, most of them are not supported well. To introduce you to them, let look at the more commonly used ones.

a:link {
color : green ;
}
a:hover {
text-decoration : none ;
color : red ;
}
a:visited {
text-decoration : none ;
color : #00ffff ;
}
a:active {
color : blue ;
}
a:visited:active {
color : blue ;
}

The first option will change all links to green text, this is not the same as just using a as <a name="top">top</a> would not be changed to green. The :hover applies the style to anything the mouse in hovered over. In IE 6 this only worked on links. The :visited applies a style to links that have been visited by the user in the past, it is important to use this so users know what pages they have seen before. The the second last one, :active, applies a style to an element as it is being clicked. IE has a bug and this only works on links. The last example is to show you that they can be combined.

IE 7 for the first time introduced support for :first-child, to apply styling to the an element is if it the first one inside it's parent. In the following example if the first child is a paragraph element is is made bold.

p:first-child {
font-weight : bold ;
}
div:target {
background : #f3f3ee ;
}

The second rule use uses the :target pseudo classe, this means that if the part of the url after the # matches the id or name of the element it will get a different background color. This does not work in IE, but it still nice to use it for all other browsers.

Pseudo Elements

The pseudo elements are different from the pseudo classes in they they select elements from the pages that don't really exists as (X)HTML tags. You will soon see what I mean by this after the first two examples.

p:first-letter {
font-size : 2em ;
}
p:first-line {
font-weight : bold ;
}

The :first-letter pseudo element allows us to style the first letter of an element, in this example the first letter of a paragraph is changed so it font size is twice as large. With a bit of extra styling it is possible to create a look seen in some books where the first letter is larger, a special front, and dropped down to fill the while top corner. The second example will style the first line of a paragraph to make it bold.

There are two other pseudo elements, that are quite fun to use, they are the :before and :after. For example if you were writing an play script and you put the classes romeo and juliet on each paragraph you could use this.

.romeo:before {
content : 'Romeo : " ' ;
}
.romeo:after {
content : ' "' ;
}
.juliet:before {
content : 'Juliet : " ' ;
}
.juliet:after {
content : ' "' ;
}

You can see this in action at the end of the Pseudo Classes Examples where you will find all the CSS shown here in use.