:nth-child(N) (CSS selector)

Description

This pseudo-class matches elements on the basis of their positions within a parent element’s list of child elements. The pseudo-class accepts an argument, N, which can be a keyword, a number, or a number expression of the form an+b. For more information, see Understanding :nth-child Pseudo-class Expressions.

If N is a number or a number expression, :nth-child(N) matches elements that are preceded by N-1 siblings in the document tree.

The following example selectors are equivalent, and will match odd-numbered table rows:

tr:nth-child(2n+1) {
  ⋮ declarations
}
tr:nth-child(odd) {
  ⋮ declarations
}

This example selector will match the first three rows of any table:

tr:nth-child(-n+3) {
  ⋮ declarations
}

This example selector will match any paragraph that’s the first child element of its parent element:

p:nth-child(1) {
  ⋮ declarations
}

This is, of course, equivalent to the selector p:first-child.

tr:nth-child(odd) {
  ⋮ declarations
}

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments

Comments on this post are closed.