Numbers & Units
Do math on numbers while Sass tracks their units for you.
Syntax
@use 'sass:math'; math.div(100%, 3)Sass numbers can carry units and Sass understands unit arithmetic. Adding 2px + 3px gives 5px, and dividing compatible units cancels them out.
Unit rules
- You cannot add incompatible units:
2px + 3emis an error. - Multiplying
pxbypxgivespx*px, which is invalid CSS — multiply by a unitless number instead. - Use the
mathmodule for division and other operations.
Example
@use 'sass:math';
$columns: 12;
$gutter: 24px;
.col {
width: math.div(100%, $columns); // 8.3333333333%
padding: math.div($gutter, 2); // 12px
margin-top: $gutter * 2; // 48px
}When to use it
- A developer calculates responsive padding by multiplying a base unit variable by a scale factor instead of hand-computing each pixel value.
- A mixin converts a pixel value to rems automatically using Sass division so the codebase stays unit-consistent as the base font size changes.
- A grid system uses Sass math to compute column widths as percentages from a total number of columns, avoiding brittle hard-coded values.
More examples
Basic arithmetic with units
Performs multiplication and safe division on a base pixel variable to derive related spacing values without magic numbers.
@use 'sass:math';
$base: 16px;
.container {
padding: $base * 1.5; // 24px
margin: math.div($base, 2); // 8px
max-width: $base * 50; // 800px
}px-to-rem converter function
A custom function uses sass:math division and unit multiplication to convert any pixel value to the equivalent rem.
@use 'sass:math';
@function rem($px, $base: 16) {
@return math.div($px, $base) * 1rem;
}
h1 { font-size: rem(32); } // 2rem
p { font-size: rem(14); } // 0.875remComputed column widths
Combines a @for loop with math.percentage and math.div to generate all twelve column-width utility classes mathematically.
@use 'sass:math';
$cols: 12;
@for $i from 1 through $cols {
.col-#{$i} {
width: math.percentage(math.div($i, $cols));
}
}
Discussion