Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Control Directives and Maps

Sass @if, @else and Conditions

Add logic to Sass with @if, @else if and @else: conditions, comparison and boolean operators, truthiness rules, conditional mixins and the modern inline if() function.

Up to now Sass has been declarative: you list values and rules. Real design systems also need decisions: use a dark text color on light backgrounds, add a border only when a flag is set, generate the large size only if it is enabled. Sass supports this with control directives. This lesson covers the decision-makers, @if and @else; the next one covers repeating things with loops.

@if and @else

SCSS
$theme: dark;

body {
  @if $theme == dark {
    background: #0f172a;
    color: #e2e8f0;
  } @else {
    background: white;
    color: #0f172a;
  }
}

The condition after @if is an expression. If it is true (anything except false or null) the first block runs; otherwise the @else block runs. Only one branch ends up in the output; the other disappears at compile time. Note that this is not the same as a CSS media query: the choice is made when you compile, not when the page loads.

@else if

Chain conditions with @else if (two words):

SCSS
@mixin badge($level) {
  @if $level == "error" {
    background: #fee2e2;
    color: #991b1b;
  } @else if $level == "warning" {
    background: #fef3c7;
    color: #92400e;
  } @else if $level == "success" {
    background: #dcfce7;
    color: #166534;
  } @else {
    background: #e2e8f0;
    color: #334155;
  }
}

Sass checks the conditions from top to bottom and runs the first branch that matches. A final @else is the catch-all.

Writing conditions

Use the operators from Data types and operators:

Operator Example
== and != $size == large, $mode != dark
<, <=, >, >= $columns > 6
and $a > 0 and $a < 10
or $theme == dark or $force-dark
not not $disabled

Parentheses group expressions: @if ($a or $b) and $c { ... }.

Truthiness

Only false and null are falsy. Everything else, including 0, "" and (), is truthy. This differs from JavaScript and trips people up:

SCSS
$count: 0;
@if $count { /* runs! 0 is truthy */ }
@if $count > 0 { /* runs only when positive */ }

Compare explicitly ($count > 0) rather than relying on truthiness.

Conditions in a function

Conditions with optional arguments

Conditions shine with optional parameters, where null means "not provided":

SCSS
@mixin box($padding, $border: null, $radius: null) {
  padding: $padding;
  @if $border {
    border: 1px solid $border;
  }
  @if $radius {
    border-radius: $radius;
  }
}

.plain { @include box(8px); }
.card  { @include box(16px, $border: #cbd5e1, $radius: 8px); }

For properties, you often do not need @if at all: a declaration whose value is null is simply omitted from the output. So border-radius: $radius; alone gives the same result when $radius is null.

Feature flags and configuration

A library or theme can switch features on and off with boolean variables set through !default:

SCSS
$enable-shadows: true !default;
$enable-rounded: true !default;

.btn {
  padding: 8px 16px;
  @if $enable-rounded { border-radius: 6px; }
  @if $enable-shadows { box-shadow: 0 1px 3px rgb(0 0 0 / .2); }
}

Bootstrap's Sass source works exactly this way, and a user turns features off by setting the flags before loading the library. See module configuration.

Checking what exists

The sass:meta module can test whether something exists, which keeps libraries from failing on optional pieces:

SCSS
@use "sass:meta";

@if meta.variable-exists(brand) { /* a local variable named $brand exists */ }
@if meta.global-variable-exists(brand) { /* a global one exists */ }
@if meta.function-exists(rem) { /* a function named rem exists */ }
@if meta.mixin-exists(center-flex) { /* ... */ }

And meta.type-of($value) lets you branch on the type of an argument (for example, accepting either a number or a map).

The inline if() function

For tiny choices, an @if block is a lot of code. Sass has a function for picking one of two values. The modern syntax (added in recent Dart Sass versions to follow the CSS if() specification) names the condition with sass():

SCSS
.btn {
  color: if(sass($dark): white; else: black);
}

Older code uses the legacy if($condition, $if-true, $if-false) form, which still compiles but is deprecated and prints a warning. For compatibility with old versions of Sass, an @if / @else block is the safest choice, and it also works when you need to output several declarations.

Modern inline if() and optional arguments

Notice that .plain has no border or border-radius lines at all, because a null value drops the declaration.

A conditional can also pick selectors and rules

@if is not restricted to declarations. You can wrap whole rules or even @include calls, which is handy for optional utilities:

SCSS
$include-print-styles: true;

@if $include-print-styles {
  @media print { .no-print { display: none; } }
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which values are falsy in Sass?

    Only false and null are falsy. Zero and empty strings are truthy.
  2. 2. How do you write 'else if' in Sass?

    Use @else if with a space, written after the closing brace of the previous block.
  3. 3. What happens to a declaration whose value is null?

    A null value drops the declaration, which makes optional arguments easy.
  4. 4. When is an @if decided?

    Sass conditions are evaluated at compile time. Use media queries or custom properties for run-time decisions.

Summary

  • @if, @else if and @else choose which styles are output, at compile time.
  • Conditions use comparison and and / or / not; only false and null are falsy.
  • null values drop declarations, which pairs well with optional arguments.
  • Boolean flags with !default make libraries configurable; sass:meta tests whether things exist.
  • The inline if(sass(cond): a; else: b) function is the modern one-liner; the comma form is deprecated.

Next: Each, for and while loops