Black and white photograph of the loops of a wooden rollercoaster

Unlike scripting languages such as JavaScript and , vanilla CSS cannot loop back on itself. The lack of this feature often means that portions of your site stylesheets must be written out in long, tedious routines that force you to cut, paste, and alter CSS declarations, only to have to change them all again when a detail in the markup or CSS changes.

Thankfully, Sass does have loops, which can generate a great number of lines in your stylesheet almost instantly.

Loop Syntax

Sass loops are part of the scripting language’s “control directives”. A Sass for loop is very similar to a for loop in JavaScript:

@for $i from $n to $p {
    // do something
}

The first variable, $i is an incrementor: it keeps track of how many times the loop has run through. The second and third variables are the start and end values of the loop. The incrementor must always be a variable, but the start and end values can be hard-coded:

@for $i from 1 to 4 {
    // do something
}

Alternatively, you could the through syntax:

@for $i from 1 through 4 {
    // do something
}

The difference between the two is subtle, but important: in the to syntax, the loop will give up as soon as it hits the final number, whereas through will do just as the name indicates, proceeding though for the final loop.

To execution:

At the top of the loop: “What’s the value of $i? Is it less than 4? It is? Then I’ll keep going. Wait, now it’s 4. I have to stop, I can’t go through the loop again”

Through execution:

“What’s the value of $i? Is it equal to 4? Not yet? In that case, I’ll keep going. Oh, now it’s 4? Okay, I’ll do this loop one more time, then finish.”

Using Loops: A Reading Rainbow

An obvious use of loops is to create nth-child selectors in CSS. Let’s say we wanted to create a rainbow effect in a navigation bar, with each link having a different background color. (Note that this is strongly inadvisable from a design perspective: we’re simply using it here as an exercise.)

While there are many ways to achieve this, let’s say we want to use Sass. Create a new pen at CodePen, and in the HTML pane write:

nav>a[href="#"]*5

…and immediately press the TAB key, then fill in the text for each link. The result might look like this:

<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Book</a>
  <a href="#">Classes</a>
  <a href="#">Resources</a>
</nav>

Make sure the CSS pane is set to accept Sass, then write the following:

nav { 
	display: flex;
    a { 
    	    flex: 1;
    	    text-align: center;
    	    padding: 1rem;
    }
}

This ensures that each link takes up the same amount of space. Go ahead and customize the appearance of the links however you wish; I’ll concentrate on the backgrounds here.

We want the background color of each link to proceed in order around the HSL color wheel, so I’ll change the Sass code to the following:

nav {
    display: flex;
    a {
        flex: 1;
        text-align: center;
        padding: 1rem;
        @for $i from 1 through 5 {
            $rot: $i * 72;
             &:nth-child(#{$i}) { 
                background: hsl($rot, 100%, 50%);
                }
          }
    }
}

The Sass generates:

nav a:nth-child(1) { 
    background: hsl(72, 100%, 50%); 
}
nav a:nth-child(2) {
    background: hsl(144, 100%, 50%);
}

The result looks like this:

Aside from changing aspects of the loop and looking at the results directly in the CodePen preview pane, the easiest way to understand what’s going on is to see the complete generated CSS code. Click Share and choose the Export option at CodePen to download a complete copy of the files for yourself.

As you can see, using loop can generate a lot of CSS very quickly, making it extremely useful in developing stylesheets.

There are a number of new features in this example, including the use of Sass math and “echoing” variable values directly in CSS code. I’ll explore both of those in more detail, together with more variations of Sass loops, such as @each and @while, in future articles.

Photograph by Alexis Gravel, licensed under Creative Commons.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/vEWVdd