Sub topic 11
Loops and conditionals
This chapter covers Sass's control directives: @if, @else, @each, @for and @while. They let the compiler make decisions and repeat output, so you write a pattern once and get many CSS rules.
It assumes you know Sass variables, maps, interpolation (#{}) and basic mixins. It also assumes you can read the compiled CSS that sass produces.
Why control directives exist
Plain CSS has no loops or branches. Sass runs these directives at compile time, so none of them reach the browser. The browser receives only the expanded rules.
| Directive | Use it to |
|---|---|
| `@if` / `@else if` / `@else` | Choose which declarations to emit |
| `@each` | Repeat for every item in a list or map |
| `@for` | Repeat over a range of integers |
| `@while` | Repeat until a condition becomes false |
Conditionals with @if
@if evaluates an expression and emits its block when the result is truthy. Chain further cases with @else if, and finish with @else.
@mixin theme($mode) {
@if $mode == dark {
background: #111;
color: #eee;
} @else if $mode == light {
background: #fff;
color: #222;
} @else {
@error "Unknown mode: #{$mode}";
}
}
.panel {
@include theme(dark);
}This compiles to:
.panel {
background: #111;
color: #eee;
}Passing theme(blue) stops compilation and prints the @error message. A failing build is better than silently producing no styles.
Operators in conditions
- Comparison:
==,!=,<,<=,>,>= - Logic:
and,or,not(Sass does not use&&,||or!)
@use 'sass:map';
$spacings: (sm: 0.5rem, md: 1rem);
@function spacing($key) {
@if not map.has-key($spacings, $key) {
@error "No spacing named #{$key}.";
}
@return map.get($spacings, $key);
}
.card {
padding: spacing(md);
}Here not map.has-key(...) guards against typos in token names. The .card rule compiles to padding: 1rem;.
Truthiness
Only false and null are falsy in Sass. Everything else is truthy, including 0, the empty string "" and an empty list.
@if 0 {
.runs { color: red; }
}This rule is emitted, because 0 is truthy. JavaScript habits cause this mistake often. If you want to test for zero, write @if $n == 0.
Strings compare by content, not by quotes: "dark" == dark is true. Numbers compare with units taken into account, so 1in == 96px is true, but 1px == 1em is false.
The if() function
For a single value, the if() function is shorter than a full @if block:
$compact: true;
.row {
padding: if($compact, 0.25rem, 1rem);
}The result is padding: 0.25rem;. Use it for one value. Switch to @if as soon as you need several declarations.
Looping with @each
@each takes each item in a list or map in turn.
$breakpoints: (
sm: 36rem,
md: 48rem,
lg: 64rem
);
@each $name, $min in $breakpoints {
@media (min-width: $min) {
.hide-#{$name}-up {
display: none;
}
}
}Compiled output:
@media (min-width: 36rem) {
.hide-sm-up {
display: none;
}
}
@media (min-width: 48rem) {
.hide-md-up {
display: none;
}
}
@media (min-width: 64rem) {
.hide-lg-up {
display: none;
}
}Each map entry is a key and value pair. Writing two variables, $name, $min, destructures the pair. With a single variable, you get the whole pair as a two-item list.
Maps of maps
Real design tokens are often nested. Loop over the outer map and read the inner one with map.get:
@use 'sass:map';
$buttons: (
primary: (bg: #3366cc, fg: #fff),
danger: (bg: #cc3333, fg: #fff)
);
@each $name, $cfg in $buttons {
.btn-#{$name} {
background: map.get($cfg, bg);
color: map.get($cfg, fg);
}
}This produces .btn-primary and .btn-danger, each with its own colors. Adding a variant means adding one map entry. You do not copy a rule.
Lists and destructuring
A list of lists can also be destructured:
$icons: (home 1rem), (search 1.25rem), (menu 1.5rem);
@each $name, $size in $icons {
.icon-#{$name} {
width: $size;
height: $size;
}
}The outer list is comma-separated. Each inner list is space-separated. @each assigns the first inner item to $name and the second to $size.
Counting with @for
@for loops over integers. It has two forms:
from 1 through 3includes 3.from 1 to 3stops before 3, so it covers only 1 and 2.
@use 'sass:math';
@for $i from 1 through 4 {
.col-#{$i} {
width: math.percentage(math.div($i, 4));
}
}This emits .col-1 with width: 25%, then .col-2 with 50%, .col-3 with 75% and .col-4 with 100%. The loop uses math.div instead of /, as the earlier arithmetic chapter explained.
The start can be larger than the end. @for $i from 3 through 1 counts down. The loop variable is always an integer, and the bounds must be unitless numbers.
Indexing a list
Sass has no built-in index variable in @each. When you need the position, use @for with list.nth:
@use 'sass:list';
$shades: #f0f4ff, #c7d6ff, #8aa8ff;
@for $i from 1 through list.length($shades) {
.shade-#{$i} {
background: list.nth($shades, $i);
}
}Sass lists are 1-indexed. list.nth($shades, 0) is an error.
Looping with @while
@while repeats as long as its condition is truthy. It is the least common directive, because you must change the condition yourself:
$i: 1;
@while $i <= 3 {
.gap-#{$i} {
gap: $i * 4px;
}
$i: $i + 1;
}Forgetting $i: $i + 1 makes the compiler loop forever. Prefer @for when the count is known. Use @while only when the stopping point depends on a computed value.
Edge cases and common errors
- Output size. Each iteration writes real CSS. A loop of 100 steps over 5 properties gives 500 declarations. Generate only what you use.
- Interpolation is required in selectors. Writing
.col-$iis a syntax error. Write.col-#{$i}. Property values do not need it. - Scope. A variable assigned inside a loop or
@ifblock is local to that block. To update an outer variable, assign it with!global, or declare it at the top level first. In the@whileexample above,$iis declared outside the loop for this reason. - Map order. Maps keep the order you wrote.
@eachvisits entries in that order, which matters when later rules override earlier ones. - Unit errors.
$i * 4pxis fine.$i + 4pxwith an incompatible unit raises a compile error. Check units when a loop mixes numbers from different sources.
Putting it together
A common pattern combines a map, @each and @if:
$alerts: (
info: #3366cc,
warn: #cc9900,
error: #cc3333
);
@each $kind, $color in $alerts {
.alert-#{$kind} {
border-left: 4px solid $color;
@if $kind == error {
font-weight: 700;
}
}
}All three classes get a colored left border. Only .alert-error gets bold text. The map holds the data, the loop writes the rules, and the condition handles the one exception.
Exercise
Given $sizes: (sm: 1rem, md: 2rem, lg: 3rem);, write Sass that emits a .p-sm, .p-md and .p-lg class setting padding to the matching value. Then say what @for $i from 1 to 4 iterates over and whether @if 0 runs its block.
Show answer
Use @each $name, $value in $sizes { .p-#{$name} { padding: $value; } }. The loop @for $i from 1 to 4 iterates over 1, 2 and 3, because to excludes the end value (through would include 4). @if 0 does run its block, because only false and null are falsy in Sass.
Exercise
A teammate writes @while $i < 3 { .step-#{$i} { order: $i; } } with $i: 0; declared above it. The compiler never finishes. What is wrong, and what is a simpler alternative?
Show answer
The loop never changes $i, so the condition stays true forever. Add $i: $i + 1; inside the loop body. A simpler alternative is @for $i from 0 to 3, which manages the counter for you.