Conditions: @if and @else
A condition lets a mixin or a function produce different styles depending on its arguments. @if checks an expression while compiling: if it is true, the block is output; otherwise Sass goes to @else. The browser sees only the chosen branch.
@if and @else
A button mixin can produce a filled or an outlined button. Add it to styles/abstracts/_mixins.scss:
// styles/abstracts/_mixins.scss
@mixin button($color, $outline: false) {
padding: 8px 16px;
border: 2px solid $color;
@if $outline {
color: $color;
background: transparent;
} @else {
color: white;
background: $color;
}
}// styles/components/_buttons.scss
@use "../abstracts/mixins";
.btn-primary {
@include mixins.button(#2563eb);
}
.btn-secondary {
@include mixins.button(#2563eb, $outline: true);
}// styles/main.scss
@use "components/buttons";.btn-primary {
padding: 8px 16px;
border: 2px solid #2563eb;
color: white;
background: #2563eb;
}
.btn-secondary {
padding: 8px 16px;
border: 2px solid #2563eb;
color: #2563eb;
background: transparent;
}<style>
.btn-primary {
padding: 8px 16px;
border: 2px solid #2563eb;
color: white;
background: #2563eb;
}
.btn-secondary {
padding: 8px 16px;
border: 2px solid #2563eb;
color: #2563eb;
background: transparent;
}
</style>
<button class="btn-primary">Buy</button>
<button class="btn-secondary">Details</button>@else is optional: without it, nothing is output when the condition is false.
Several branches: @else if
For more than two variants add @else if. Sass checks the conditions from top to bottom and takes the first true one:
// styles/abstracts/_mixins.scss
@mixin text-size($size) {
@if $size == "small" {
font-size: 14px;
} @else if $size == "large" {
font-size: 20px;
} @else {
font-size: 16px;
}
}// styles/components/_cards.scss
@use "../abstracts/mixins";
.card-note {
@include mixins.text-size("small");
}// styles/main.scss
@use "components/cards";.card-note {
font-size: 14px;
}Operators in conditions
| Operator | Meaning | Example |
|---|---|---|
==, != | Equal, not equal | $size == "large" |
<, >, <=, >= | Comparing numbers | $width >= 768px |
and | Both are true | $a > 0 and $b > 0 |
or | At least one is true | $theme == "dark" or $contrast |
not | The opposite | not $outline |
Sass uses the words and, or, not — not && and ! as in JavaScript.
What counts as true
Only two values are false in Sass: false and null. Everything else is true — including 0, an empty string "" and an empty list. This differs from JavaScript, where 0 and "" are false.
Common mistake
Comparing numbers with different units can give an unexpected answer. 16px == 16 is false: a number with a unit does not equal a number without one. And comparing incompatible units, like $width > 50% when $width is 600px, stops the build with an error. Keep the units consistent in the values you compare, or compare plain numbers.