Sass Math — Complete Guide
In this tutorial, you will learn about Sass Math. We cover key concepts, practical examples, and best practices to help you master this topic.
Sass math enables calculations with units, division, modulo, rounding, and comparison using the sass:math module for fluid and precise CSS values.
What You'll Learn
- The sass:math module and its functions
- Unit-aware calculations
- Division with math.div()
- Rounding functions (floor, ceil, round)
- Min, max, clamp calculations
- Percentage conversion
- Random number generation
Why It Matters
- Precise math reduces manual calculations
- Unit-safe operations prevent errors
- Fluid typography requires complex math
- Random values enable dynamic designs
Real-World Use
- A fluid typography system calculates clamp values
- A grid system generates column percentages
- A spacing scale computes from a base unit
- A random color generator creates varied palettes
flowchart LR A[sass:math] --> B[Arithmetic] A --> C[Rounding] A --> D[Comparison] A --> E[Random] B --> F[div, calc] C --> G[ceil, floor, round] D --> H[min, max, clamp] E --> I[random]
Math Operations
Code Example: Basic Math with Units
@use 'sass:math';
// Division: always use math.div()
$width: 100%;
$columns: 12;
$col-width: math.div($width, $columns); // 8.33333%
// Old syntax (deprecated): $width / $columns
// New syntax: math.div($width, $columns)
// Multiplication with units
$base-spacing: 8px;
$spacing-2: $base-spacing * 2; // 16px
$spacing-3: $base-spacing * 3; // 24px
$spacing-4: $base-spacing * 4; // 32px
// Addition and subtraction (same units)
$container: 1200px;
$gutter: 32px;
$content-area: $container - $gutter; // 1168px
// calc() for runtime calculations
.element {
width: calc(100% - #{$gutter}); // calc(100% - 32px) at runtime
}
// Percentage conversion
$value: 0.75;
.element {
width: math.percentage($value); // 75%
}
// Unit conversion helper
@function px-to-rem($px, $base: 16px) {
@return math.div($px, $base) * 1rem;
}
.element {
font-size: px-to-rem(16px); // 1rem
padding: px-to-rem(24px); // 1.5rem
margin: px-to-rem(32px, 14px); // 2.28571rem (custom base)
}
Expected output: math.div() ensures unit-safe division. Percentage conversion and px-to-rem functions create maintainable math-based values.
Code Example: Fluid Typography with Math
@use 'sass:math';
// Fluid typography calculation
@function fluid-type($min-size, $max-size, $min-vw: 320px, $max-vw: 1200px) {
$slope: math.div($max-size - $min-size, $max-vw - $min-vw);
$intercept: $min-size - $slope * $min-vw;
@return clamp(#{$min-size}, #{$intercept} + #{$slope * 100vw}, #{$max-size});
}
// Modular scale
$base: 1rem;
$ratio: 1.25; // Major third
h1 { font-size: fluid-type(2rem, $base * math.pow($ratio, 5)); }
h2 { font-size: fluid-type(1.5rem, $base * math.pow($ratio, 4)); }
h3 { font-size: fluid-type(1.25rem, $base * math.pow($ratio, 3)); }
h4 { font-size: fluid-type(1rem, $base * math.pow($ratio, 2)); }
// Or use a function with power
@function ms($step, $base: 1rem, $ratio: 1.25) {
@return $base * math.pow($ratio, $step);
}
h1 { font-size: ms(5); } // 1rem * 1.25^5 = 3.051rem
h2 { font-size: ms(4); }
h3 { font-size: ms(3); }
// Fluid spacing
@function fluid-space($min, $max) {
@return fluid-type($min, $max);
}
.section {
padding: fluid-space(1rem, 4rem);
margin-bottom: fluid-space(2rem, 6rem);
}
Expected output: math.pow() computes exponential modular scales. The fluid-type function generates responsive clamp() values. math.div() calculates slopes for fluid interpolation.
Code Example: Grid Calculations
@use 'sass:math';
// Flexible grid system
$columns: 12;
$gutter: 16px;
@function col-width($span, $total: $columns) {
@return math.percentage(math.div($span, $total));
}
@function gutter-width($span) {
@return $gutter * ($span - 1);
}
@for $i from 1 through $columns {
.col-#{$i} {
width: col-width($i);
padding-left: math.div($gutter, 2);
padding-right: math.div($gutter, 2);
}
.col-offset-#{$i} {
margin-left: col-width($i);
}
}
// Nested grids
$nested-total: $columns;
@for $parent from 1 through $columns {
@for $child from 1 through $columns {
.col-#{$parent}-#{$child} {
$parent-width: math.div($parent, $nested-total);
$child-width: math.div($child, $nested-total);
width: math.percentage($parent-width * $child-width);
}
}
}
// Aspect ratio helper
@function aspect-ratio($width, $height) {
@return math.percentage(math.div($height, $width));
}
.video-embed {
padding-bottom: aspect-ratio(16, 9); // 56.25%
}
.square {
padding-bottom: aspect-ratio(1, 1); // 100%
}
Expected output: Grid column widths are calculated as percentages. Nested grids compute proportional widths. Aspect-ratio helper generates padding-bottom values for responsive embeds.
Code Example: Rounding and Random
@use 'sass:math';
// Rounding
.element {
width: math.round(33.33%); // 33%
height: math.ceil(33.33%); // 34%
opacity: math.floor(0.85); // 0.8 (if using 0-1 scale)
}
// Round to decimal places
@function round-to($value, $decimals: 2) {
$factor: math.pow(10, $decimals);
@return math.div(math.round($value * $factor), $factor);
}
.element {
width: round-to(33.33333%); // 33.33%
}
// Clamp (like CSS clamp but at compile time)
.element {
width: math.clamp(100px, 50%, 800px); // Limits value to range
}
// Min and max
.element {
width: math.min(100%, 800px); // Smallest value
height: math.max(400px, 50vh); // Largest value
}
// Random values
$random-color: rgb(math.random(255), math.random(255), math.random(255));
$random-opacity: math.random() / 100; // Random between 0 and 1 (integer)
// Random with seed (useful for deterministic results)
$seed: 42;
$deterministic: math.random($seed); // Same value every time (with same seed)
// Random within range
@function random-range($min, $max) {
$range: $max - $min;
@return $min + math.random($range);
}
@for $i from 1 through 5 {
.particle-#{$i} {
$duration: random-range(2, 5);
animation-duration: #{$duration}s;
}
}
Expected output: Rounding functions ensure consistent percentage values. math.clamp(), math.min(), and math.max() provide compile-time bounds checking. math.random() generates varied values for dynamic designs.
Common Mistakes
- Using / for division — The / operator is deprecated for division. Always use math.div().
- Mixing incompatible units — math.div(16px, 2em) produces invalid CSS. Ensure units are compatible or use unitless values.
- Using math.percentage on values with units — math.percentage(0.75) is correct. math.percentage(12px) produces unexpected results.
- Not using math.pow() for exponents — Sass does not have an exponent operator. Use math.pow($base, $exponent).
- Forgetting that math.random() returns integers — math.random() returns an integer. math.random() with no argument returns a float between 0 and 1.
- Using math inside calc() unnecessarily — If calc() is needed at runtime, pass Sass-computed values into calc() with interpolation.
- Not rounding percentages — Unrounded percentages (33.33333%) are technically fine but can cause sub-pixel rounding issues in some browsers.
Practice Questions
- How do you perform division in modern Sass? Use math.div($numerator, $denominator) from the sass:math module.
- What does math.percentage(0.75) return? 75%.
- How do you calculate an exponential value in Sass? Use math.pow($base, $exponent) (e.g., math.pow(1.25, 3)).
- What is the difference between math.round() and math.floor()? round() rounds to the nearest integer. floor() always rounds down.
FAQ
Mini Project
Build a complete fluid typography and spacing system using Sass math. Create: (1) a fluid-type function using math.div() for slope calculation, (2) a modular scale using math.pow(), (3) a fluid-space function for responsive padding/margin, (4) a grid system with math.percentage() column widths, (5) an aspect-ratio helper function, (6) random particle animation durations using math.random(), and (7) a round-to function that rounds to specified decimal places. Build a sample page that uses all functions. Verify the compiled CSS contains correct calculated values.
What's Next
Continue with Lesson 11: Sass Color Functions to learn color manipulation in Sass.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro