CSS Reference ยท Pseudo-classes
The :nth-last-child() pseudo-class
Reference for the CSS :nth-last-child() pseudo-class: match elements by position counted from the last sibling, with an+b formulas and live examples.
The :nth-last-child() pseudo-class works exactly like :nth-child(), except that it counts from the last sibling backwards. The last child is position 1, the one before it is position 2, and so on.
This is the right tool when you care about the end of a list without knowing its length: "the last three items", "all but the last two", or "stripes that always finish on the same colour".
li:nth-last-child(-n + 3) { font-weight: bold; }
Try it
Both lists have different lengths, yet the same rules always hit the right items.
Syntax
:nth-last-child( <nth> [ of <selector-list> ]? ) { }
- Arguments: the same
odd,even, integer oran+bforms as:nth-child(), and the same optionalof S. - Specificity: (0, 1, 0), plus the most specific selector of
Sif present.
Values
| Syntax and arguments | Description |
|---|---|
1 |
The last child. Same as :last-child. |
2 |
The second child from the end. |
-n + 3 |
The last three children. |
n + 3 |
Every child except the last two. |
odd / even |
Odd or even positions counted from the end. |
of S |
Count only siblings that match S. |
Usage notes
- Quantity queries. Combine it with
:nth-child()to react to the number of items.li:nth-last-child(n + 4):first-childmatches the first item only when the list has at least four items, andli:nth-last-child(-n + 3):first-childwhen it has three or fewer. - Stable stripes at the end. Standard
odd/evenstriping starts from the top. If the bottom row must always be the same colour, count from the end. - Position counts all siblings.
p:nth-last-child(2)needs the second-to-last child to be a<p>. To count only one tag, use:nth-last-of-type(). - Dynamic content. Items added at the end shift every match, which is useful for "fade out the last few entries" effects.
Browser support
Supported in every browser. The of S argument is Baseline since 2023.
Related
:nth-child()โ counted from the start:nth-last-of-type()โ from the end, one tag only:last-child- Lesson: Structural Pseudo-classes