selector pseudo-class allows you to select elements based on their position in the set of children of their parent. It accepts an argument in the form of
an + b. How exactly does it work? Let me explain.
In very simple words, the expression
an + b matches every ath element in the set starting from the bth element keeping in mind that (i) the index numbering starts at 1 (ii) zero and negative values do not represent any element (iii) text and non-element nodes are not counted. The following corollaries exist:
acan be zero or an can be omitted – in which case there is no "every ath element in the set" clause and only the bth element is matched.
acan be negative – in which case every ath element is matched going backwards, towards non-existing elements.
bcan be zero or negative – in which case the matching starts from a non-existing element.
- The argument can be
even– which represent the expressions
2n + 1and
These rules apply to the following CSS3 pseudo-classes:
:nth-child()– matches elements that are nth child of their parent.
:nth-last-child()– matches elements that are nth child of their parent counting backwards, i.e. 1 represents the last element, 2 represents second last, and so on.
:nth-of-type()– matches elements that are nth element of their type among the children of their parent.
:nth-last-of-type()– matches elements that are nth element of their type among the children of their parent counting backwards.
Use the following demo to test the arguments.