iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

@if / @else

Sass control directives — @if, @for, @each, @while — let you generate CSS algorithmically. The right tool for design-token systems and utility classes.

if / for / each / while in real CSS

EXAMPLE
@@use 'sass:list';
@@use 'sass:math';
@@use 'sass:string';

/* 1) @if — conditional output */
@@mixin theme($mode) {
    @@if $mode == 'dark' {
        background: #0b0b0b;
        color: #eee;
    } @@else if $mode == 'light' {
        background: #fff;
        color: #111;
    } @@else {
        @@error "Unknown theme: #{$mode}";
    }
}

.dark  { @@include theme('dark'); }
.light { @@include theme('light'); }

/* 2) @for — generate a spacing scale */
@@for $i from 0 through 8 {
    .m-#{$i} { margin: #{$i * 0.25}rem; }
    .p-#{$i} { padding: #{$i * 0.25}rem; }
}

/* 3) @each — iterate a list */
$brand-colors: ('primary': #0ea5e9, 'success': #10b981, 'danger': #ef4444);

@@each $name, $value in $brand-colors {
    .bg-#{$name}    { background: $value; }
    .text-#{$name}  { color:      $value; }
    .border-#{$name}{ border:     1px solid $value; }
}

/* 4) @each on nested lists */
$breakpoints: ('sm' 640px, 'md' 768px, 'lg' 1024px, 'xl' 1280px);

@@each $bp in $breakpoints {
    $name:  list.nth($bp, 1);
    $width: list.nth($bp, 2);

    @@media (min-width: $width) {
        @@for $i from 1 through 12 {
            .#{$name}\\:col-#{$i} { grid-column: span #{$i}; }
        }
    }
}

/* 5) @while — type scale with a ratio */
$step:  0;
$size:  0.875rem;
$ratio: 1.25;

@@while $step < 6 {
    .text-#{$step} { font-size: $size; }
    $size: $size * $ratio;
    $step: $step + 1;
}

/* 6) Combine with @@function for clean intent */
@@function rem($px) { @@return math.div($px, 16) * 1rem; }
.p-md { padding: rem(20); }

Why it matters

Sass loops generate utility CSS at build time, not run time — you ship the same lean stylesheet whether the loop emitted 4 rules or 400. Source code stays declarative; output stays small.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
@if $theme == 'dark' {
    color: white;
} @else {
    color: black;
}
Try it Yourself »

Discussion

Loading…