Conditional logic in SCSS – @if statements and @for, @each, and @while loops.
@if statements in SCSS
SCSS supports conditional logic with the @if directive. Your stylesheet can output different styles based on variable values.
Basic @if statement
$theme: dark;
body {
@if $theme == dark {
background-color: #000;
color: #fff;
} @else {
background-color: #fff;
color: #000;
}
}
Background and text colours depend on the $theme variable.
Nested @if statements
You can chain conditions with @else if:
$primary-color: blue;
.button {
@if $primary-color == red {
background-color: #e74c3c;
} @else if $primary-color == green {
background-color: #2ecc71;
} @else {
background-color: #3498db;
}
}
The button background changes based on $primary-color.
Loops in SCSS
Loops let you generate repetitive CSS – useful for grid systems, colour utility classes, and anything that follows a pattern.
The @for loop
@for runs a set number of times:
@for $i from 1 through 12 {
.col-#{$i} {
width: 100% / 12 * $i;
}
}
This generates width classes for a 12-column grid.
The @each loop
@each loops over items in a list or pairs in a map:
$colors: (red: #e74c3c, green: #2ecc71, blue: #3498db);
@each $key, $color in $colors {
.text-#{$key} {
color: $color;
}
}
Creates a text colour class for each entry in the $colors map.
The @while loop
@while keeps running as long as a condition is true:
$i: 1;
@while $i <= 12 {
.col-#{$i} {
width: 100% / 12 * $i;
}
$i: $i + 1;
}
Same result as the @for example above, using a @while loop instead.
Combining conditional logic with other SCSS features
Conditional logic works inside mixins, functions, and nested selectors:
Example: dynamic mixin with @if
@mixin button-color($color) {
@if $color == dark {
background-color: #000;
color: #fff;
} @else {
background-color: #fff;
color: #000;
}
}
.button {
@include button-color(dark);
}
The mixin applies different styles based on the colour argument.
Best practices for conditional logic in SCSS
- Keep it simple: too much conditional logic makes stylesheets hard to follow. Use it where it genuinely saves repetition.
- Clear naming conventions: descriptive variable names matter more when they drive conditions.
- Document your code: comment complex conditions or loops so you (and your team) can follow them later.
Conditional logic turns SCSS from a preprocessor into something closer to a programming language. Use it for theme switching, generating utility classes, and anywhere repetitive CSS follows a pattern.

