CSS :nth-child() Selector

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

The :nth-child() CSS pseudo-class matches one or more elements based on their position among a group of siblings.

This CSS tutorial explains how to use the CSS selector called :nth-child with syntax and examples.

The CSS :nth-child selector allows you to target an element that is the nth child element within its parent.

element:nth-child(value) { style_properties }

Definition and Points of Interest

  • :nth-child iterates through elements starting from the top of the source order. The only difference between it and :nth-last-child is that the latter iterates through elements starting from the bottom of the source order.
  • The :nth-child selector is very similar to :nth-of-type but with one critical difference: it is less specific. In our example above they would produce the same result because we are iterating over only .module elements, but if we were iterating over a more complex group of siblings, :nth-child would try to match all siblings, not only siblings of the same element type. This reveals the power of :nth-child—it can select any sibling element in an arrangement, not only elements that are specified before the colon.
  • The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.n can be a number, a keyword, or a formula.
  • The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n, plus the positive number of elements you want to select. For example, li:nth-child(-n+3) will select the first 3 li elements.

Example -