clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

For, while, and each loops in Sass

Filed under: HTML/CSS— Tagged with: iteration, sass

Sass looping syntax guide.

I got news for you, loops is Sass are not that different from other languages. for loops are pretty much the same in all languages, see an interesting for loop timeline, the saga starts as early as 1957. In Sass, things are more like in Ruby than in, say, JavaScript, thus the loop syntax looks more plain English than unfathomable jargon.

For loop

The really straightforward syntax is:

@for $var from <start> through <end>

Let’s Imagine that we have to print styles for eight columns, with an ascending number in the end, and a different width for each column.

WIth a for loop shortens this ordeal significantly:

@for $i from 1 through 8 {
  $width: percentage(1 / $i);

  .col-#{$i} {
    width: $width;
  }
}

It emits the following CSS:

.col-1 {
  width: 100%;
}
.col-2 {
  width: 50%;
}
.col-3 {
  width: 33.333%;
}
.col-4 {
  width: 25%;
}
.col-5 {
  width: 20%;
}
.col-6 {
  width: 16.666%;
}
.col-7 {
  width: 14.285%;
}
.col-8 {
  width: 12.5%;
}

That breaks down to:

  • @for $i from 1 through 8 - Start from number 1 and run the loop 8 times.
  • $width: percentage(1 / $i) - $i is the increment variable, it can be called anything, though.
  • .col-#{$i} - The columns number, note that the $i is interpolated, whenever you have another character 'touching' the variable, or it's between quotes, it needs to be interpolated.

While loop

While loop runs while a condition is met.

$num: 4;

@while $num > 0 {
  .module-#{$num} {
    content: '#{$num}';
  }

  $num: $num - 1;
}

Each loop

Foreach loops work by consuming an array, arrays in Sass are called lists. Here we have a list of names, and then we iterate that list as long as it lasts:

$list: arnold sylvester dolf jean chuck

@mixin author-imgs {
  @each $manly-man in $list
  .photo-#{$manly-man} {
    background: image-url("avatars/#{$manly-man}.png") no-repeat;
  }
}

.author-bio {
  @include author-imgs();
}

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • console.log('Smash the patriarchy!')
  • I love u!