My :nth-child Selectors Formula

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?!").

Really appreciate CSS Tricks post ( and their tester (, but being an engineer, I just work better with input/output. So I thought I'd write this down:

:nth-child({every_nth}n + {starting_from**})

** omit if every_nth == starting_from

or, if you wanna make it look more ruby-like:

:nth-child("#{every_nth}n + #{starting_from == every_nth ? 0 : starting_from}")

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: Check it out!


comments powered by Disqus