:nth-last-child
Published on
The :nth-last-child
pseudo-class works just like :nth-child
, but instead of counting from the beginning, it counts from the end of the parent element.
This comes in handy when you want to style an element based on how far it is from the end, and you donโt know how many siblings it has.
We can also select a group of elements at the end by using -n
. For example, if we do :nth-last-child(-n + 3)
, it goes to the third to last child (the +3), and the
-n` goes in reverse, selecting every element from there.
How it works
Just like :nth-child
, you can use various patterns:
:nth-last-child(1)
- The last element (same as:last-child
):nth-last-child(2)
- The second-to-last element:nth-last-child(odd)
- Every odd element counting from the end:nth-last-child(even)
- Every even element counting from the end:nth-last-child(3n)
- Every third element counting from the end:nth-last-child(-n+3)
- The last 3 elements
Browser support
:nth-last-child
has been supported since IE9, so youโre fine using it in production ๐.