Calculate: n'th-child with an SCSS mixin

Have you ever encountered an issue where a client wants alternating colours on individual elements, but you don’t have the opportunity to edit the HTML itself to add a class or an ID, so you must target them via nth-child, excluding a javascript fix.

I have, and I have a solution for you.

What you currently do:

Looking at the SCSS at the bottom of the styles you will see a list of positional selectors. You currently type each one and manually calculate the nth child. This can be a problem if you want to add/remove colours.

If you suddenly have 9 blocks and you would like different colours on each one you would need to change the positional selector to :nth-child(9n+#). But that would mean you will have to change every selector from 6n to 9n so you don't have overlapping styles. So my solution calculates the amount of colours you want to display on your nth-child and automatically assign the nth child values. That then gives you the ability to edit one area and effect all your nth-child under that mixin. This is a major time save once its setup.

What you should do:

Lets explain what the variable and mixin is doing.

$alternating-colors: is the variable that contains all the colours you want to display as nth-child selectors. The amount of colours here will be calculated and automatically define the nth-child position selector.

@mixin alternating-background: is a mixin that calculates the amount of colours in the variable, creates position selectors per colour and automatically assigns the correct colour to the correct positional selector.

It does a @for control directive which then calculates each increment ($i) from the first value in your variable colour then calculates how many colours you have in your variable using length($alternating-colors). Within that it then calculates the length of the variable colours again, giving you the value :nth-child(6n) then it works out which increment of