Loop with @for

Developers commonly use for-loops to repeat a block of styles a certain number of times based on a start and end value.

Sass

@for $i from 1 through 10 {
  .box-#{$i} {
    background-color: adjust-hue(tomato, $i * 20);
  }
}

CSS

.box-1  { background-color: #ffa047; }
.box-2  { background-color: #ffde47; }
.box-3  { background-color: #e3ff47; }
.box-4  { background-color: #a6ff47; }
.box-5  { background-color: #68ff47; }
.box-6  { background-color: #47ff63; }
.box-7  { background-color: #47ffa0; }
.box-8  { background-color: #47ffde; }
.box-9  { background-color: #47e3ff; }
.box-10 { background-color: #47a6ff; }

from – Starting value
through – Inclusive of end value
to – Exclusive of end value
#{$i} – Interpolation format


Loop with @each

@each loops iterate through collections of data, like a lists or maps.

Sass

// List of values
$teachers: ('andrew', 'alena', 'joel', 'danielle', 'nick', 'aisha');

@each $teacher in $teachers {
  .teacher-#{$teacher} {
    background-image: url('img/#{$teacher}.jpg');
  }
}

CSS

.teacher-andrew   { background-image: url("img/andrew.jpg"); }
.teacher-alena    { background-image: url("img/alena.jpg"); }
.teacher-joel     { background-image: url("img/joel.jpg"); }
.teacher-danielle { background-image: url("img/danielle.jpg"); }
.teacher-nick     { background-image: url("img/nick.jpg"); }
.teacher-aisha    { background-image: url("img/aisha.jpg"); }

Loop Through Data in a Map with @each.

Sass

// Map of values
$themes: (
  'ent': #79ccf5,
 'arch': #fd6fa6, 
  'edu': #23bbae,
  'sim': #2377bb,
  'soc': #ada3f0,
  'games': #3cb144,
);

// Looping through the list
@each $theme, $color in $themes {
  .icn-#{$theme} {
    color: $color;
  }

CSS

.icn-ent   { color: #79ccf5; }
.icn-arch  { color: #fd6fa6; }
.icn-edu   { color: #23bbae; }
.icn-sim   { color: #2377bb; }
.icn-soc   { color: #ada3f0; }
.icn-games { color: #3cb144; }

To make this clever approach include other selectors, we’ll place it inside of a mixin and apply a few changes.

Sass

// Colors
@mixin themes($map) {
  @each $theme, $color in $map {
    &-#{$theme} {
      color: $color;
    }
  } 
}

.icn {
  @include themes($themes);
}

Loop with @while

$count: 0;

@while $count < 5 {
    .length-#{$count} {
        width: (10 * $count) + px;
    }

    $count: $count + 1;
}