CSS: nth-child selector

By Xah Lee. Date: . Last updated: .

nth-child

tag:nth-child(n)

match element x if:

  • tag matches x.
  • x is nth child.

tag is optional. It can be a simple selector (selecting by tag name, id, class etc) or a compound selector (combination of tag name, id, class etc). If empty, it means the universal selector (* any tag).

Count starts at 1.

/* nth column in a table */
.align6033 td:nth-child(2) {
 text-align: right;
 background-color: silver;
}
NameCountfarm
Rick78dog
David1372cat
Marc10298fish
Jackson31317bats
Lee41156fish

Even, odd

tag:nth-child(even)

match element x if:

  • tag matches x.
  • x's sibling order rank is even.

🟢 TIP: this is useful for table rows, columns, or list items. [CSS: Styling HTML Table]

.xeven6308 tr:nth-child(even) {
 background-color: silver;
}
even
cat1
cat2
cat3
cat4
cat5
cat6
tag:nth-child(odd)

match element x if:

  • tag matches x.
  • x's sibling order rank is odd.
.xodd0118 tr:nth-child(odd) {
 background-color: silver;
}
odd
cat1
cat2
cat3
cat4
cat5
cat6

nth-child(An)

tag:nth-child(An)

every Ath.

🛑 WARNING: no space before n.

/* every 3rd */
.x3rd2886 tr:nth-child(3n) {
 background-color: silver;
}
every 3rd
cat1
cat2
cat3
cat4
cat5
cat6
cat7
cat8
cat9
cat10

With offset

tag:nth-child(An + B)
  • A is the step size.
  • B is the offset.
  • n goes from 0 to infinity.
/* every 2n , starting at offset 5 */
.offset3511 tr:nth-child(2n+5) {
 background-color: silver;
}
2n, offset 5
cat1
cat2
cat3
cat4
cat5
cat6
cat7
cat8
cat9
cat10
cat11
cat12

example. first 3

.allbefore4161 tr:nth-child(-n+3) {
 background-color: silver;
}
first 3
cat1
cat2
cat3
cat4
cat5

example. rest starting at 4th

.allrest4201 tr:nth-child(n+4) {
 background-color: silver;
}
first 3
cat1
cat2
cat3
cat4
cat5

nth-child(arg of selector)

CSS selectors by child or sibling rank

CSS. Selectors

Selector types
Simple selectors
Combinators
Selector list
Nesting syntax
Special selector
Misc