Sass·Sass from variables to a design system

Control flow

Generate repetitive rules with @each, @for and @if.

Intermediate 12 min read Lesson 7 of 300 Challenge included
What you will be able to do
  • Use @each for spacing and colour scales.
  • Use @for for numbered utilities.
  • Use @if for conditional output.
  • Keep generated selectors predictable.

In plain English

Sass can loop at build time. Use @each for token maps, @for for a fixed range and @if for conditional output. Generated CSS is still static, which keeps runtime cost at zero.

utilities.scssSCSS
$sizes: (sm: 8px, md: 16px);

@each $name, $value in $sizes {
  .p-#{$name} { padding: $value; }
}

@for $i from 1 through 3 {
  .mt-#{$i} { margin-top: #{$i * 4}px; }
}
Your turn

Generate padding utilities

Medium

Loop over a $sizes map and generate .p-name classes.

SCSS · starter
@each $name, $value in $sizes {
Check your understanding before moving on.
Knowledge checkQuestion 1

Which directive loops over a map?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Modules
Lesson 7 of 300 · 0% of course