I'm running a marathon for charity!   Donate Here.

CSS: Select the Last Odd Child

January 9, 2014
1 minute read

How did I never see this before? In my need for random pieces of code throughout the day, I had this problem arise. I needed a responsive navigation pattern to format correctly when I had an odd number of links. I was using this "clean grid" pattern and I originally wrote that you need an even amount of links in order for this pattern to look good. Not anymore!

Thanks to the magic of CSS3, we can target two things at once: :nth-last-child(1) - then we combine it with :nth-child(odd) to target both a last child and an odd selector. Pretty slick, huh? So put it together and we get this: ul.nav li:nth-last-child(1):nth-child(odd) a

This let me target the last element ONLY if it were an odd number. If it wasn't an odd number, then no harm no foul.

Here's the reference I found with a bit more info: http://stackoverflow.com/questions/8641003/css-last-odd-child