Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Operators and math

Sass can calculate values while compiling: double a gap, split a width into columns, convert pixels to rem. The browser receives only the result. Arithmetic works with the usual operators, and more complex math comes from the built-in sass:math module.

Arithmetic operators

+, -, * and % work on numbers, including numbers with units:

// styles/main.scss
$gap: 16px;
 
.card {
  padding: $gap;
  margin-bottom: $gap * 2;
  border-width: $gap - 14px;
}
.card {
  padding: 16px;
  margin-bottom: 32px;
  border-width: 2px;
}

Units are kept: 16px * 2 is 32px. Adding numbers with the same unit is fine; adding px to em is not.

Division with math.div

In CSS the / sign is often not division but a separator: font: 16px/1.5 sans-serif, grid-area: 1 / 3. That is why dividing with / in Sass is deprecated. Divide with the math.div() function from the sass:math module, which you connect with @use at the top of the file:

// styles/main.scss
@use "sass:math";
 
$container: 960px;
 
.column {
  width: math.div($container, 3);
}
 
.half {
  width: math.div(100%, 2);
}
.column {
  width: 320px;
}
 
.half {
  width: 50%;
}

math. is the namespace of the module: every function of sass:math is called through it. Modules get their own chapter later.

Other functions of sass:math

FunctionWhat it doesExample and result
math.round()Rounds to an integermath.round(12.6px) → 13px
math.floor(), math.ceil()Rounds down, upmath.ceil(12.1px) → 13px
math.percentage()Turns a fraction into percentmath.percentage(0.25) → 25%
math.min(), math.max()Smallest, largestmath.max(8px, 12px) → 12px
math.abs()Removes the minusmath.abs(-4px) → 4px

A practical example — the width of one column out of twelve:

// styles/main.scss
@use "sass:math";
 
.col-4 {
  width: math.percentage(math.div(4, 12));
}
.col-4 {
  width: 33.3333333333%;
}

Comparison and strings

==, !=, <, >, <= and >= compare values and return true or false — they are used in conditions later. The + operator also joins strings: "icon-" + "home" gives "icon-home".

Common mistake

Sass cannot add units that depend on the page, such as 100% and 20px: their sum is known only in the browser. The expression 100% - 20px stops compiling with the error 100% and 20px have incompatible units. Leave such calculations to the browser with calc() — Sass substitutes the variables and keeps the function:

// styles/main.scss
$sidebar: 240px;
 
.content {
  width: calc(100% - #{$sidebar});
}
.content {
  width: calc(100% - 240px);
}

The #{} brackets insert a variable's value into the text; this is called interpolation. Inside calc() Sass also accepts a plain $sidebar, but #{} makes the intent clear.

Thanks for reading!

Donate to the site — we work hard for you.