CSS Pseudo-Classes

Pseudo-classes take Type Selectors one step further by not only targeting a particular HTML element, but also targeting a state of an element. Examples of state that can be targeted include elements that are the first, last or only child of another element, as well as the different states of an anchor element. A Pseudo-Class takes the following form.

selector:pseudo-class {
   property: value;
}

Anchor Pseudo-Classes

Anchor elements have four states that can be targeted, an unvisited link, a visited link, a link where a mouse is hovering over it and an active link. CSS can be applied to each of the states as shown below. Here, unvisited links have blue text with no underline, visited links have red text with no underline, whilst links in a hover or active state are underlined.

a:link {
   color: blue;
   text-decoration: none;
}
a:visited {
   color: red;
   text-decoration: none;
}
a:hover {
   text-decoration: underline;
}
a:active {
   text-decoration: underline;
}

It should be noted that the 'hover' state works with a number of other elements including 'div' and 'button' elements.

:first-child, :last-child and :nth-child

The :first-child, :last-child and :nth-child Pseudo-classes target child elements of another element. :first-child and :last-child target the first and last child of another element, whilst the :nth-child Pseudo-class targets a specified child. In the case of :nth-child the specified child could be a number, for example 2, or, alternatively it could be used to target all odd or even children.

The four example CSS rules below target list items. The first list item is given a top border that is 1px thick, solid and black. The last list item is given a similarly styled bottom border. The second item in the list is given red text. Finally, all odd list items are given a green background.

li:first-child {
   border-top: 1px solid black;
}
li:last-child {
   border-bottom: 1px solid black;
}
li:nth-child(2) {
   color: red;
}
li:nth-child(odd) {
   background-color: green;
}

More Pseudo-Classes

The above Pseudo-Classes are just a selection of what is available. For details of more Pseudo-classes, see the links below.