SyntaxStudy
Sign Up
SASS / SCSS @if, @else if, and @else Directives
SASS / SCSS Beginner 1 min read

@if, @else if, and @else Directives

SASS provides full control flow with `@if`, `@else if`, and `@else` directives. These allow conditional CSS output based on variable values, argument types, or any SASS expression. Conditional logic is most commonly used inside mixins and functions to adapt their output based on the arguments they receive. The condition in an `@if` block is any SASS expression that evaluates to a truthy or falsy value. In SASS, only `false` and `null` are falsy — every other value, including `0` and empty strings, is truthy. Comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`) and logical operators (`and`, `or`, `not`) work as expected. Conditional logic can also be expressed with the `if()` built-in function for single-line ternary-style expressions: `color: if($dark-mode, #fff, #333)`. The `if()` function evaluates both its then-value and else-value eagerly, however, so it cannot be used in place of `@if` when either branch would cause an error if evaluated.
Example
// ── @if / @else if / @else in a mixin ────────────────────────────────────────

@mixin theme-colors($theme) {
    @if $theme == 'light' {
        background: #ffffff;
        color     : #333333;
        border    : 1px solid #e0e0e0;
    } @else if $theme == 'dark' {
        background: #1a1a2e;
        color     : #e0e0e0;
        border    : 1px solid #444;
    } @else if $theme == 'sepia' {
        background: #fdf6e3;
        color     : #5c4b37;
        border    : 1px solid #d4c5a9;
    } @else {
        @warn "Unknown theme `#{$theme}`. Falling back to light.";
        background: #ffffff;
        color     : #333333;
    }
}

.page-light { @include theme-colors('light'); }
.page-dark  { @include theme-colors('dark'); }
.page-sepia { @include theme-colors('sepia'); }

// ── @if for type checking in a function ──────────────────────────────────────

@use 'sass:meta';
@use 'sass:math';

@function to-rem($value) {
    @if meta.type-of($value) != 'number' {
        @error "to-rem() expects a number, got #{meta.type-of($value)}.";
    }

    @if math.is-unitless($value) {
        @return ($value / 16) * 1rem;
    } @else if math.unit($value) == 'px' {
        @return math.div($value, 16px) * 1rem;
    } @else if math.unit($value) == 'rem' {
        @return $value;  // already rem
    } @else {
        @error "to-rem() cannot convert unit `#{math.unit($value)}`.";
    }
}

// ── Ternary-style if() function ───────────────────────────────────────────────

$dark-mode: false;

.text {
    color      : if($dark-mode, #ecf0f1, #2c3e50);
    background : if($dark-mode, #2c3e50, #ffffff);
}