Skip to content

Calculating nth-child CSS Selector Formulae

I did quite a lot of maths at school. I wasn’t amazing at it but because I knew I wanted to work in computers I thought it would be handy. Fast forward 16 years and I now realise that I’ve forgotten most of it. I can still do the basics – and having developed a few different video games I can still do some basic maths related to physics & mechanics. But there’s plenty that I don’t remember.

Today I wanted to calculate a formula for an nth-child selector using css. I understand the principals, but because the pattern was strange I was getting a bit confused. Eventually I found a maths website that explained a simple way to create formulae for simple number patterns so I thought I’d document so I have something to refer to in the future.

For more info on nth-child selectors check out this post on CSS Tricks about how nth-child selectors work

The pattern I was working with was 2, 6, 10, 14, 18 … – I had a starting point (which wasn’t 1) and a consistent difference between the items.

How to Turn a Pattern Into a Formula

The formula is a + ( n - 1 ) * d where:

  • a = first number in the sequence
  • n = multiplier (the same n we already use in css formulae)
  • d = common difference between numbers in the pattern

Applying this to the pattern I showed earlier means a = 2 (the first number in the sequence), and d = 4 (the common difference between the numbers in the sequence).

Which then means we do the following:

a + (n - 1) * d =
2 + (n - 1) * 4 =
2 + (4n - 4) =
4n - 2

So my nth-child selector ended up being 4n – 2. In hindsight it was pretty straight forward – but it took far too long to work out so I’m glad I have a nice simple method for calculating these things in the future :).

Categories

Tips, Web Design

Ben View All

Ben is a lifelong Nintendo fan who also likes to build websites, and develop games. He also buys way too much Lego.

2 thoughts on “Calculating nth-child CSS Selector Formulae Leave a comment

  1. Quick question, is there any performance benefit to doing this type of logic with pure CSS or using a library like JQuery.

    Part of me thinks that JQuery would be easier to read and less complicated.

    Thoughts?

    • I suspect there’s a small performance benefit – plus you won’t get the flash of unstyled content (since the styles will be added immediately and not have to wait for the js). Also – CSS will work when javascript is disabled.

Leave a Reply

Your email address will not be published. Required fields are marked *