CSS: nth-child selector
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; } Name Count farm Rick 78 dog David 1372 cat Marc 10298 fish Jackson 31317 bats Lee 41156 fish
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 cat 1 cat 2 cat 3 cat 4 cat 5 cat 6
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 cat 1 cat 2 cat 3 cat 4 cat 5 cat 6
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 cat 1 cat 2 cat 3 cat 4 cat 5 cat 6 cat 7 cat 8 cat 9 cat 10
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 cat 1 cat 2 cat 3 cat 4 cat 5 cat 6 cat 7 cat 8 cat 9 cat 10 cat 11 cat 12
example. first 3
.allbefore4161 tr:nth-child(-n+3) { background-color: silver; }
| cat | 1 |
| cat | 2 |
| cat | 3 |
| cat | 4 |
| cat | 5 |
example. rest starting at 4th
.allrest4201 tr:nth-child(n+4) { background-color: silver; }
| cat | 1 |
| cat | 2 |
| cat | 3 |
| cat | 4 |
| cat | 5 |
nth-child(arg of selector)
CSS selectors by child or sibling rank
CSS. Selectors
Selector types
Simple selectors
- CSS: type selector (tag name)
- CSS: universal selector (* any tag)
- CSS: class selector (.x)
- CSS: ID selector (#)
- CSS: attribute selector ([x])
Combinators
- CSS: descendant selector (space)
- CSS: child selector (>)
- CSS: adjacent sibling selector (+)
- CSS: subsequent sibling selector (~)
Selector list
Nesting syntax
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, last child, only child selectors
- CSS: nth-child selector
- CSS: nth-child arg of selector
- CSS: nth-of-type selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: :not negation selector
- CSS: :has descendant selector