For Loops in Sass

There tends to be a lot of repetition in CSS. Because of its static nature, we tend to write the same rules over and over. But as I’m about to show you, a little Sass function knowledge can go a long way.

Fortunately Sass has brought many concepts from more advanced programming languages over to the world of CSS. It’s still the same old CSS that gets compiled, but we can use arrays and loops to keep from repeating ourselves. This not only saves time for the person writing the code initially, it also makes it easier to update and maintain.

As an example, we’re going to take five sections on a page and give each of them a unique background color using a for loop.

Arrays

Sass supports arrays as variables. Let’s start by creating an array of our chosen colors:

$backgrounds: (
  #A0F6AD,
  #FFFFB5,
  #4F7E86,
  #F16F62,
  #080053
);

It’s best if we can power the loop off of this array. If we end up adding sections and colors later, all we need to do in our CSS is add the new color to our array.

The For Loop

Companion Cube

Next we’ll write a for loop to iterate over the colors in our array and assign them as background colors to the sections.

@for $i from 1 through length($backgrounds) {
  .section-#{$i} {
    background-color: nth($backgrounds, $i);
  }
}

CodePen Example

See the Pen Sass For Loops by Alan Crissey (@TheRealAlan) on CodePen.

Don’t get too carried away

Sass functions are great. They help us accomplish simple tasks like this with ease, while keeping it maintainable. This can be taken many steps further and applied in plenty of helpful ways. However, think before you get too carried away. If someone else will be working with your code later and you’ve loaded it up with Sass mixins that are packed full of complex functions, it’s going to be harder for them to understand. The purpose of preprocessors like Sass is to help with our workflows, not hinder them. If you can abstract away 99% of your CSS to the point where it’s unrecognizable, more power to you. But I wouldn’t want to be the person to inherit that code. Code responsibly.