0
0
SASSmarkup~5 mins

Arithmetic operations in SASS

Choose your learning style9 modes available
Introduction

Arithmetic operations let you do math with numbers in your styles. This helps you create flexible and dynamic designs.

When you want to calculate widths or heights based on other sizes.
When you need to add or subtract spacing like margins or padding.
When you want to multiply or divide values to scale elements easily.
When you want to create responsive designs that adjust automatically.
When you want to keep your code clean by avoiding repeated numbers.
Syntax
SASS
$result: <number> <operator> <number>;

Operators include + (add), - (subtract), * (multiply), / (divide), and % (modulus).

Use variables or numbers directly. Always include spaces around operators for clarity.

Examples
Adds 100 pixels and 20 pixels to get 120 pixels.
SASS
$width: 100px + 20px;
Divides 50% by 2 to get 25%.
SASS
$half: 50% / 2;
Multiplies 10 rem units by 2 to get 20 rem.
SASS
$double: 10rem * 2;
Subtracts 30 pixels from 80 pixels to get 50 pixels.
SASS
$difference: 80px - 30px;
Sample Program

This example shows how to use arithmetic to set padding as half the base size, margin as base size plus 8 pixels, and width as the smaller of 100% minus 40 pixels or 600 pixels.

SASS
@use 'sass:math';

$base-size: 16px;
$padding: $base-size / 2;
$margin: $base-size + 8px;

.container {
  font-size: $base-size;
  padding: $padding;
  margin: $margin;
  width: math.min(100% - 40px, 600px);
}
OutputSuccess
Important Notes

Always keep units consistent when doing arithmetic (e.g., px with px, %, or rem).

Division with / can sometimes be confused with CSS slash notation; use parentheses to clarify.

You can use the math module for advanced math functions like min(), max(), and pow().

Summary

Arithmetic operations let you do math in Sass to create flexible styles.

Use +, -, *, /, and % with numbers and variables.

Keep units consistent and use parentheses to avoid confusion.