SASS Tutorial

Nth-Child background Color Mixin

Posted on by

Not really sure how to intro this one, so just going to jump right to the point…I made a mixin to gradually change the background color of elements based off nth-child. It’s kind of a neat trick is you have a long list of links or categories that you want to change colors as it grows. Let’s take a looksie…

The Mixin

The mixin has 2 variables to define, $max-count and $color-frequency. $max-count is going to be what the maximum amount of colors you’re going to want in your list of colors. $color-frequency is how intense you want the color changes to be. So, the lower the number is for this variable, the more extreme your color change is going to be, the higher it is, the more gradual the color changes will be. It’s pretty fun to play with the 2 variables and see what kind of color combos you can come up with.


// $max-count is the maximum amount of colors you'll want
// $color-frequency is how intense you want the color change to be. Lower # = more intense changes
@mixin colors($max-count, $color-frequency){
  $color: 360/$max-count;

  @for $i from 1 through $max-count {
    &:nth-child(#{$max-count}n + #{$i}) {
      background: hsl(($i - 1)*($color / $color-frequency), 80%, 60%);

This mixin can look a little funky, so I’ll break it down a bit. Basically, we’re using that $i variable to collect the count for how many nth-child elements we actually have and stops at our max-count variable that we define when including the mixin.

Then, I’m using hsl (hue, saturation, lightness) to define the colors. You’ll notice the only thing I’m changing is the hue of the color to keep the color changes a bit more subtle and not too extreme. You can definitely play around with the saturation and lightness percentages to try and get the color scheme you’re going for.

So, as our mixin keeps spitting out nth-childs, it adds to each which results in the hue of each nth-child being slightly changed resulting in the rainbow-ish effect all of the list items are getting.

The next step is to apply it. So, I wrote a huge list that allows 5 items per line to demonstrate all of the color changes and included the mixin and defined my max amount of colors and color frequency and shabam, you have lot’s of colors.

Not a whole lot of uses for this, but it’s a fun one to play around with and can maybe be modified and get creative with it. I’ve embedded my CodePen so you can experiment with some of the variables and values yourself.

See the Pen NTH-CHILD BACKGROUND COLOR MIXIN by Jason Kinney (@jason-kinney) on CodePen.

Leave a Reply