My :nth-child Selectors Formula

21 April 2016

I've been looking up how :nth-child works at least once per month (sometimes per week) for as long as I can remember. Every time I'm working with a grid of some kind I inevitably come to a point where I need to clear every nth element (and then mutter to myself "ah, crap. How do I do this, again?!").

This makes a bit more sense - to me anyways. With this I can say "I need every 4th element starting from the first." So:

every_nth = 4
starting_from = 1
:nth-child(4n +1)

Or "I need every third element"

every_nth = 3
starting_from = 0
:nth-child(3n + 0) => :nth-child(3n)

Hopefully that helps someone other than just myself. One thing to make clear is this formula won't work if you need something like "the first five elements..." (:nth-child(-n+5)), but I've never had to do that, so...

On a final note, another option would be to use a grid or framework that just avoids :nth-child all together! I'm sure there's a few out there, but I recently saw one from a friend, Will McMahan over at Thoughtbot called Cask: https://cask.readme.io. Check it out!