@if and @else

Output different styles based on a condition.

Syntax@if $cond { } @else if $other { } @else { }

@if outputs a block only when a condition is true. Chain alternatives with @else if and @else. This is control flow for your stylesheet, most useful inside mixins and functions.

The if() function

For a quick inline choice, the if($condition, $if-true, $if-false) function returns one of two values — like a ternary.

Example

Example · css
@mixin theme($mode) {
  @if $mode == 'dark' {
    background: #222;
    color: #eee;
  } @else if $mode == 'high-contrast' {
    background: #000;
    color: #fff;
  } @else {
    background: #fff;
    color: #333;
  }
}

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

// Inline ternary
.badge { color: if(true, #CC6699, gray); }

When to use it

  • A theme mixin outputs light or dark color values based on a boolean $dark-mode variable, switching the entire palette at compile time.
  • A button mixin uses @if to apply an outline style when a $variant argument equals 'outline', otherwise it renders a filled button.
  • A responsive helper checks whether a breakpoint argument is 'mobile' or 'desktop' and emits the correct max-width or min-width media query.

More examples

Simple @if / @else

Compares a string variable to 'dark' and outputs the corresponding color scheme at compile time.

Example · css
$theme: dark;

body {
  @if $theme == dark {
    background: #121212;
    color: #e0e0e0;
  } @else {
    background: white;
    color: #111;
  }
}

Multi-branch @if / @else if

Uses @else if chains to map an alert type string to the appropriate background and text color combination.

Example · css
@mixin alert-color($type) {
  @if $type == success {
    background: #d1fae5; color: #065f46;
  } @else if $type == warning {
    background: #fef3c7; color: #92400e;
  } @else if $type == error {
    background: #fee2e2; color: #991b1b;
  } @else {
    background: #f3f4f6; color: #374151;
  }
}

Inline if() function

Uses the single-expression if() function for compact inline conditionals that return a value rather than a block of rules.

Example · css
$rounded: true;
$rtl:     false;

.card {
  border-radius: if($rounded, 8px, 0);
  text-align:    if($rtl, right, left);
}

Discussion

  • Be the first to comment on this lesson.