Skip to content
Tutorials Center
My learning

Topics

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".

CSS
li:nth-last-child(-n + 3) {
  font-weight: bold;
}

Try it

Styling from the end

Both lists have different lengths, yet the same rules always hit the right items.

Syntax

CSS
:nth-last-child( <nth> [ of <selector-list> ]? ) { }
  • Arguments: the same odd, even, integer or an+b forms as :nth-child(), and the same optional of S.
  • Specificity: (0, 1, 0), plus the most specific selector of S if 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-child matches the first item only when the list has at least four items, and li:nth-last-child(-n + 3):first-child when it has three or fewer.
  • Stable stripes at the end. Standard odd/even striping 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.