Conditional Logic with @if, @else, and @while
Sass supports conditional compilation through @if, @else if, and @else. These directives can select which declarations or rules are emitted based on Sass values.
The @while directive repeats a block while a condition remains true. Although useful in some algorithms, it is generally less readable than @each or @for for ordinary stylesheet generation.
Conditions are evaluated during compilation. They cannot respond directly to a user's browser interaction or a CSS custom property's runtime value.
Keep conditional stylesheet generation deterministic. Complicated conditional trees can make the final CSS difficult to reason about, especially when several conditions generate overlapping selectors.
Use @error for invalid configuration and @warn when an input is allowed but potentially problematic. These messages help catch design-system mistakes early.
@mixin surface-theme($theme) {
@if $theme == dark {
background: #171717;
color: #f5f5f5;
} @else if $theme == light {
background: #ffffff;
color: #222222;
} @else {
@error "Unsupported theme: #{$theme}";
}
}
.panel {
@include surface-theme(dark);
}@error stops compilation with a useful message.
Explicit validation is preferable to silently generating incorrect output when a function or mixin accepts a restricted set of values.When does Sass evaluate an `@if` condition?