Working with Pseudo-Classes

The CSS pseudo-classes allow us to style elements, or parts of elements, that exist in the document tree without using JavaScript or any other scripts. A pseudo-class start with a ":" (colon).

The most comonly used pseudo-classes are :first-child and :last-child.

The :first-child pseudo-classe matches an element that is the first child element of some other element.

In the following example, the selector matches any <p> element:

The HTML:

<div id="parent"> <p>First paragraph</p> <p>Second paragraph</p> <p>Third paragraph</p> <p>Fourth paragraph</p> </div>

The CSS:

#parent p:first-child { color: green; text-decoration: underline; }

Result:

First paragraph

Second paragraph

Third paragraph

Fourth paragraph

The :last-child pseudo-class mathces an element that is the last child element of some other element.

In the example below, the selector will match any <p> element that is the lat child of the div element;

#parent p:last-child { color: green; text-decoration: underline; }

First paragraph

Second paragraph

Third paragraph

Fourth paragraph