:first-of-type, :last-of-type,:only-of-type

Back to the index.

How to select an element that is the first, last, or only child of its type of its parent.

  1. X:first-of-type means “the first child of its parent that is an X element.”
  2. X:last-of-type means “the last child of its parent that is an X element.”
  3. X:only-of-type means “an X element, provided it’s the only child of its parent.”

Testsheet:

div#test p:first-of-type {text-decoration: underline;}
div#test p:last-of-type {color: red;}
div#test p:only-of-type {font-weight: bold;}

And yes, an only child is also both the first and the last child and should be red, underlined, and bold.

This is the div id="test". The first paragraph should be underlined; the last red.

Add paragraph at start or add paragraph at end of test div. Click on a paragraph to remove it.

First paragraph.

Second paragraph.

And here a test case for :only-of-type.

Only child