Sub topic 7
Arithmetic and sass:math
Sass can calculate values at compile time. This chapter covers the arithmetic operators, how units behave in calculations, and the sass:math module, which replaced the old / division. It assumes you have read the chapters on variables and the Dart Sass command line, and that you can compile a .scss file.
Operators and units
Sass numbers carry units. The operators +, -, * and % work on them directly.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `+` | Add | `10px + 5px` | `15px` |
| `-` | Subtract | `1rem - 0.25rem` | `0.75rem` |
| `*` | Multiply | `4px * 3` | `12px` |
| `%` | Remainder | `10px % 3` | `1px` |
| `math.div()` | Divide | `math.div(10px, 4)` | `2.5px` |
Sass also has comparison operators (==, !=, <, >, <=, >=) and the logical operators and, or and not. These are mostly used inside @if conditions.
Unit rules matter more than the operators:
- Compatible units convert automatically. The result takes the unit of the left operand, so
1cm + 10mmis2cm. - Incompatible units, such as
10px + 5%, stop compilation with an error. - A unitless number combines with any unit.
2 * 3pxis6px. - Multiplying two values that both have units produces a compound unit.
10px * 2pxis20px*px, which is not valid CSS, and Sass reports an error when it writes the value to the output.
$gutter: 16px;
.grid {
margin: -$gutter;
padding: $gutter * 1.5 $gutter + 4px;
width: 1cm + 10mm;
}.grid {
margin: -16px;
padding: 24px 20px;
width: 2cm;
}Spacing around minus signs
Whitespace changes the meaning of -. $a - $b is subtraction. $a -$b is a space-separated list of two values, and $a-$b is read as a single variable name. Write subtraction with a space on both sides. For negation, put the minus directly against the operand, as in -$gutter.
Strings and `+`
The + operator also joins strings. If the left operand is a quoted string, the result is quoted. If it is unquoted, the result is unquoted.
$family: "Inter";
body {
font-family: $family + ", sans-" + serif;
}This compiles to font-family: "Inter, sans-serif";. Because the left operand is quoted, the whole result is one quoted string. That is not what you want in a font-family list. Prefer interpolation for building strings, which the interpolation chapter covers.
Division with `math.div`
In plain CSS, / is a separator, as in font: 12px/1.5 Arial or grid-area: 1 / 3. Sass used the same character for division, and the two meanings were ambiguous. Dart Sass deprecated / as division, so division now goes through the sass:math module.
@use 'sass:math';
.column {
width: math.div(100%, 3);
font-size: math.div(24px, 16px) * 1rem;
}.column {
width: 33.3333333333%;
font-size: 1.5rem;
}The units follow ordinary algebra:
math.div(10px, 2)is5px.math.div(10px, 2px)is5, a unitless number.math.div(10, 4px)is2.5px^-1, which is not usable CSS.
Sass keeps ten digits after the decimal point in its output, which is why you see 33.3333333333%.
> The @use 'sass:math'; line must come before any rules in the file. Without it, math.div is an undefined module error, and / between two numbers produces a deprecation warning.
Converting and stripping units
A common task is converting a unitless design number to rem. Multiplying by a unit attaches that unit. Dividing by a unit removes it.
@use 'sass:math';
$base: 16px;
@function strip-unit($value) {
@return math.div($value, ($value * 0 + 1));
}
.demo {
line-height: math.div(24px, $base);
--raw: #{math.div(24px, 1px)};
--stripped: #{strip-unit(24px)};
}.demo {
line-height: 1.5;
--raw: 24;
--stripped: 24;
}The interpolation #{} is needed for custom properties, because Sass does not evaluate their values by default. math.div(24px, 1px) is the shortest way to strip a known unit. The strip-unit helper works for any unit, because $value * 0 + 1 produces a number with the same unit and the value 1, so the units cancel.
The module also provides tools for inspecting units:
math.unit($n)returns the unit as a string, for example"px".math.is-unitless($n)returnstrueorfalse.math.compatible($a, $b)tells you whether two numbers can be combined. This is useful for validating arguments inside your own functions.
The `sass:math` function set
Beyond div, the module has the functions you would expect, plus two constants.
| Function or constant | Purpose | Example result |
|---|---|---|
| `math.round($n)` | Round to nearest integer | `math.round(4.6)` is `5` |
| `math.ceil($n)` | Round up | `math.ceil(4.1)` is `5` |
| `math.floor($n)` | Round down | `math.floor(4.9)` is `4` |
| `math.abs($n)` | Absolute value | `math.abs(-8px)` is `8px` |
| `math.min($n...)` | Smallest value | `math.min(4px, 9px)` is `4px` |
| `math.max($n...)` | Largest value | `math.max(4px, 9px)` is `9px` |
| `math.percentage($n)` | Unitless fraction to percent | `math.percentage(0.25)` is `25%` |
| `math.pow($b, $e)` | Exponent | `math.pow(2, 3)` is `8` |
| `math.sqrt($n)` | Square root | `math.sqrt(81)` is `9` |
| `math.$pi`, `math.$e` | Constants | `3.1415926536`, `2.7182818285` |
Rounding functions keep the unit, so math.round(10.6px) is 11px. This is how you avoid fractional pixel values.
A modular type scale
math.pow is a good fit for a type scale, where each step is a fixed ratio larger than the last.
@use 'sass:math';
$base-size: 1rem;
$ratio: 1.25;
@for $step from 0 through 3 {
.step-#{$step} {
font-size: math.round(math.pow($ratio, $step) * $base-size * 100) / 100;
}
}The last line has a problem. The final / 100 is a deprecated slash division, and it also rounds a rem value badly. Write it with math.div:
@use 'sass:math';
$base-size: 1rem;
$ratio: 1.25;
@for $step from 0 through 3 {
.step-#{$step} {
font-size: math.div(math.round(math.pow($ratio, $step) * $base-size * 100), 100);
}
}.step-0 {
font-size: 1rem;
}
.step-1 {
font-size: 1.25rem;
}
.step-2 {
font-size: 1.56rem;
}
.step-3 {
font-size: 1.95rem;
}Multiplying by 100, rounding, and dividing by 100 gives two decimal places.
Choosing between Sass math and CSS math
Sass arithmetic runs at compile time, so it can only use values known to the compiler. CSS calc() runs in the browser and can mix units like 100% - 2rem. The two work together. Sass handles fixed values, and calc() handles anything that depends on layout.
flowchart TDSass variables can go inside calc(): width: calc(100% - #{$sidebar}). Sass will also simplify a calc() when it can, but it leaves the call in the output when units are incompatible.
Common errors
- Undefined module
math. The@use 'sass:math';line is missing, or it appears after a style rule. - Incompatible units. An expression like
10px + 5%fails. Usecalc(10px + 5%)instead. - Invalid CSS unit like
px*px. You multiplied two dimensioned values. Multiply by a unitless number, or divide a length by a length to get a plain number first. - Division deprecation warning. Replace
a / bwithmath.div(a, b). - Precision surprises. Output is limited to ten decimal places. Round explicitly if you need a specific precision.
Exercise
Write a Sass function col-width($cols, $total: 12) that returns the width of a grid column as a percentage, rounded to two decimal places. What does col-width(5) compile to when used as width: col-width(5);?
Show answer
Use math.div and math.percentage, then round to two places: @use 'sass:math'; @function col-width($cols, $total: 12) { @return math.div(math.round(math.percentage(math.div($cols, $total)) * 100), 100); } col-width(5) computes 5/12 = 0.4166666667, which math.percentage turns into 41.6666666667%. Multiplying by 100 gives 4166.66666667%, rounding gives 4167%, and dividing by 100 gives 41.67%. The compiled output is width: 41.67%;
Exercise
What is the result of math.div(18px, 1px) * 1rem, and why is the first step useful?
Show answer
It is 18rem. math.div(18px, 1px) cancels the px unit and returns the unitless number 18. Multiplying by 1rem then attaches the rem unit. This is the standard way to swap one unit for another when the numbers are not related by a conversion factor.