SCSS by Example: Operators
Performing calculations in stylesheets with this sample code demonstrating arithmetic operators for addition, subtraction, multiplication, division, modulo operations, unit compatibility rules, and string concatenation.
Code
$base-size: 16px;
$width: 1000px;
.container {
// Division
width: $width / 2;
// Multiplication
padding: $base-size * 2;
// Addition and Subtraction
margin: $base-size + 4px;
// Modulo
z-index: 10 % 3; // Returns 1
}
// String concatenation
$font-family: sans-serif;
body {
font: 10px + 2px / 1.5 $font-family;
}Explanation
SCSS supports arithmetic operators including addition +, subtraction -, multiplication *, division /, and modulo %. These operators enable dynamic value calculation directly in stylesheets. Unit compatibility is enforced during operations: compatible units like px + px work correctly, while incompatible operations like px + em may produce unexpected results or compilation errors depending on the context.
The division operator has special handling because CSS uses slash notation in font shorthand and other contexts. SCSS performs division only when:
- The value is part of a mathematical expression with other operators
- The value is wrapped in parentheses like
(100px / 2) - The value uses a variable like
$width / 2 - The value is returned from a function call
Otherwise, the slash is preserved as-is in the CSS output. String concatenation uses the + operator, combining quoted or unquoted strings. Comparison operators ==, !=, <, >, <=, >= are available for conditional logic. Boolean operators and, or, not enable complex conditional expressions in control directives.
Code Breakdown
$width / 2 performs division because it uses a variable, compiles to 500px.$base-size * 2 multiplies 16px by 2, resulting in 32px.10 % 3 modulo operation returns remainder 1.10px + 2px / 1.5 slash preserved in font shorthand, not division.
