Selecting the last two elements with CSS

2015-04-09

nth-child() is a very handy pseudo-selector, but sometimes you need to approach things from the other end, starting from the last item. That's where nth-last-child comes to the rescue.

nth-last-child works pretty much the same way as nth-child does except it runs in relation to the last-child.

For instance nth-last-child(odd) selects every odd number starting from the very last number and counting back from there.

Recently however I was in a scenario where I needed to select only the last two items in a list. Thats where I had to get a little creative and came up with this solution:

li:nth-last-child(-n+2)

The "-n" does the magic here by flipping the counting around. So it counts down from two (which is the "+2" part) and stops after 1, instead of starting at 1 and counting up (and thus selecting every element in the list).

If you are interested in learning more about nth-last-child, mozilla has some nice documentation and also css-tricks.com