Ben
Ben is a lifelong Nintendo fan who likes to build websites, and make video games. He buys way too much Lego.
WordPress and Games
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.
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.
The formula is a + ( n - 1 ) * d
where:
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 :).
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.