Codeskill

Learn to code, step by step

Operators in SCSS: Doing the Math

Operators in SCSS. Doing arithmetic and comparisons inside your stylesheets.

The basics of operators in SCSS

SCSS supports arithmetic, comparison, and boolean operators. You can do calculations directly in your stylesheets rather than working everything out by hand.

Arithmetic operators

The arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/), and modulo (%). They are useful for sizing, spacing, and layout calculations.

Example: dynamic padding

Calculate padding from a base size:

$base-padding: 20px;

.container {
  padding: $base-padding / 2;
  margin: $base-padding * 1.5;
}

Padding is half the base; margin is one and a half times the base.

Example: responsive font size

Adjust font size relative to the viewport:

$base-font-size: 16px;

body {
  font-size: $base-font-size + (100vw / 100) - 1em;
}

Sets a base font size, then adjusts it based on viewport width.

Division in SCSS

Division with / can be ambiguous – SCSS might treat it as a CSS separator rather than a maths operation. To force division, at least one operand must be a variable or function call.

$grid-columns: 12;
$column: 4;

.column-width {
  width: (100% * $column) / $grid-columns;
}

The width of .column-width is calculated as a fraction of the total grid.

Comparison and boolean operators

SCSS also has comparison operators (==, !=, <, >, <=, >=) and boolean operators (and, or, not). These are less common in everyday styling but useful with control directives like @if, @for, @each, and @while.

Example: conditional styling

$theme: 'dark';

body {
  @if $theme == 'dark' {
    background-color: black;
    color: white;
  } @else {
    background-color: white;
    color: black;
  }
}

Background and text colour depend on the $theme variable.

Using operators with mixins and functions

Operators work inside mixins and functions for dynamic values:

Example: dynamic mixin for margins

@mixin margin-setter($size) {
  margin: $size * 1rem;
}

.container {
  @include margin-setter(2);
}

The margin is calculated as a multiplier of the base size.

Best practices when using operators

  1. Clarity is key: if an expression gets complex, break it into steps or use a function.
  2. Check the output: verify the compiled CSS matches what you intended.
  3. Use parentheses for complex calculations: makes the order of operations explicit.

Operators add flexibility to SCSS without leaving your stylesheet. Start with simple arithmetic on variables and build from there.

PreviousExtend/Inheritance in SCSS: The Art of Keeping it DRY