CSS3 :nth-child()Selectors

Complete CSS Selector Reference Manual

Example

Specify the background color of the second child element within the parent element matched by each p element:

p:nth-child(2) { background:#ff0000; }

Try it Yourself »

Definition and Usage

The :nth-child(n) selector matches the nth child element within a parent element, with no restriction on element type.

nIt can be a number, a keyword, or a formula.

Tip:See alsoSelectorsThis selector matches the nth sibling element of the same type.

Syntax

element:nth-child(n)
  • elementis the HTML element you want to select.
  • nis a parameter, which can be a keyword (such asoddoreven), or an expression (such as2n+1)。

The keywords odd and even

  • oddSelects child elements at odd positions.
  • evenSelects child elements at even positions.

Browser Support

The numbers in the table indicate the first browser version that supports the property.

Selectors
:nth-child() 4.0 9.0 3.5 3.2 9.6

Examples

More Examples


Example 1

Odd and even are keywords that can be used to match child elements whose index is odd or even (the first child of the index is 1). Here, we specify two different background colors for odd and even p elements:

p:nth-child(odd) { background:#ff0000; } p:nth-child(even) { background:#0000ff; }

Try it Yourself »

Example 2

Using the formula (an + b). Description: a represents the size of a cycle, n is a counter (starting from 0), and b is an offset. Here, we specify a background color for all p elements whose index is a multiple of 3:

p:nth-child(3n+0) { background:#ff0000; }

Try it Yourself »


Complete CSS Selector Reference Manual

other extensions