:nth-child()

Opera has a bug in these two declarations. It turns out that when you add a last-child declaration to the page with an actual style in it, this bug disappears. The last-child does not have to be defined on the same element(s); it just has to be present in the page. It also has to contain at least one style rule.

Other browsers not yet tested, except Android G2, where this trick does not work.

See the test page that is exactly equal to this page except for the last-child declaration.

And no, first-child doesn’t help.

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: red;
}

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

Test

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.