:nth-child() and :nth-of-type()

Back to the index.

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice. For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

:nth-of-type() works the same, except that it only considers element of the given type (<div> in the example).

Test sheet:

div#test > *:nth-child(3n+1) {
	color: #CB000F;

div#test div:nth-of-type(5n+2) {
	background-color: #9999ff;


The paragraphs count for the :nth-child() selector, but not for the :nth-of-type() selector. So the offshoot is:

A script adds the expected colours to every element.

Add an element to the top of the test; alternately a div and a p.