Operators

Use math, comparison, and logical operators in Sass.

Syntax$x: 10px + 5px; @if $a and not $b { }

Sass supports operators that plain CSS lacks.

Categories

  • Math: +, -, *, % (modulo), and math.div() for division.
  • Comparison: ==, !=, <, >, <=, >=.
  • Logical: and, or, not.

Math operators respect units, so 2rem + 1rem is 3rem but mixing incompatible units errors. Use these mostly inside functions, mixins, and control flow.

Example

Example · css
@use 'sass:math';

$cols: 4;
$gap: 16px;

.item {
  width: math.div(100%, $cols);   // 25%
  margin-right: $gap;
  margin-bottom: $gap * 1.5;       // 24px
}

@if $cols > 3 and $gap >= 16px {
  .grid { max-width: 1200px; }
}

When to use it

  • A developer uses Sass arithmetic to compute a sidebar's flex-basis as a percentage of the grid without opening a calculator.
  • A mixin compares an argument against a minimum value with a comparison operator and throws a warning if the constraint is violated.
  • A conditional block uses logical 'and' to check that both a width and a height are non-zero before rendering an image placeholder.

More examples

Arithmetic operators

Uses multiplication, safe division, and addition on a base pixel variable to derive spacing values without magic numbers.

Example · css
@use 'sass:math';

$base: 16px;
$cols: 12;

.sidebar {
  width: $base * 16;                       // 256px
  padding: math.div($base, 2) $base;       // 8px 16px
  margin-bottom: $base + 8px;              // 24px
}

Comparison operators in a guard

Combines comparison (<=) and logical (or) operators to validate mixin arguments and emit a warning for invalid input.

Example · css
@mixin size($w, $h: $w) {
  @if $w <= 0 or $h <= 0 {
    @warn 'size() expects positive values';
  } @else {
    width: $w;
    height: $h;
  }
}

.icon { @include size(24px); }
.avatar { @include size(48px, 48px); }

Logical operators for feature flags

Uses and + not logical operators to apply transitions only when animations are enabled and reduced-motion is not requested.

Example · css
$animations: true;
$reduced-motion: false;

.btn {
  @if $animations and not $reduced-motion {
    transition: background 0.2s ease;
  }
}

Discussion

  • Be the first to comment on this lesson.