Sub topic 11
Loops and conditionals
This chapter assumes you can write variables, maps, mixins and interpolation (#{}) in SCSS. Control directives let the compiler make decisions and repeat output, so you can generate many rules from a few lines.
Conditionals with @if
@if runs a block when its condition is true. Chain @else if and @else for other cases. Use == and != to compare, and and, or and not to combine tests.
@mixin theme($mode) {
@if $mode == dark {
background: #111111;
color: #eeeeee;
} @else if $mode == light {
background: #ffffff;
color: #111111;
} @else {
@error "Unknown mode: #{$mode}";
}
}
.page {
@include theme(dark);
}@error stops compilation with your message. This catches a typo such as theme(drak) at build time.
Looping over lists and maps with @each
@each visits every item in a list or every key and value pair in a map. Combine it with interpolation to build selectors.
$colors: (
primary: #3366cc,
danger: #cc3333
);
@each $name, $value in $colors {
.text-#{$name} {
color: $value;
}
.bg-#{$name} {
background: $value;
}
}This produces four rules: .text-primary, .bg-primary, .text-danger and .bg-danger. Adding a map entry adds both classes without any other change.
Counting loops with @for
@for counts between two numbers. The keyword decides whether the end value is included.
@for $i from 1 through 4 {
.mt-#{$i} {
margin-top: $i * 0.25rem;
}
}This generates .mt-1 through .mt-4, with margins from 0.25rem to 1rem.
| Form | Values of `$i` for `from 1` and end 4 |
|---|---|
| `from 1 through 4` | 1, 2, 3, 4 |
| `from 1 to 4` | 1, 2, 3 |
How the directives flow
You can nest the two directives. This loop skips any entry whose name starts with _:
@use 'sass:string';
$tokens: (
primary: #3366cc,
_internal: #999999
);
@each $name, $value in $tokens {
@if string.slice($name, 1, 1) != '_' {
.border-#{$name} {
border-color: $value;
}
}
}Common errors
- Writing
.text-$nameinstead of.text-#{$name}. Selectors need interpolation. - Using
towhen you wanted the last number included. Usethrough. - Looping downward with
from 4 through 1. This works, but the output order is reversed, which can change which rule wins in the cascade. - Generating large loops of unused classes. Each iteration adds real CSS, so loop only over the tokens you actually need.
Sass also has @while, which repeats until a condition is false. Prefer @each and @for, because a @while condition that never becomes false hangs the compiler.
Exercise
What CSS rules does @for $i from 1 to 3 { .col-#{$i} { width: 25% * $i; } } generate?
Show answer
It generates two rules, .col-1 { width: 25%; } and .col-2 { width: 50%; }. The keyword to excludes the end value 3, so no .col-3 rule is emitted. Changing to to through would add .col-3 { width: 75%; }.