Sass Operators: Addition, Subtraction, Multiplication, Division, and Comparison Operators Practice
As a CSS preprocessor, Sass provides rich operator support, enabling developers to perform style calculations more efficiently. The operators primarily include addition, subtraction, multiplication, division, and comparison operations. These operators follow specific precedence rules in Sass that directly impact the calculation results.
Addition, Subtraction, Multiplication, and Division Operations
Sass supports basic mathematical operations, including addition (+), subtraction (-), multiplication (×), and division (/). The precedence of these operators is similar to JavaScript, but it is important to note Sass's specific operation rules.
Addition Operation
$width = $baseWidth + $margin
$width
Sass automatically adds $baseWidth and $margin, outputting the result as a numeric value.
Subtraction Operation
$discount = 20 - $price
$discount
When $price is 30, $discount calculates to 10.
Multiplication Operation
$area = $length × $width
$area
Sass multiplies $length and $width, presenting the result as a numeric value.
Division Operation
$ratio = 100 / $count
$ratio
When $count is 5, $ratio calculates to 20.
Comparison Operations
Sass supports comparison operators used to determine the magnitude relationship between two values. Common operators include >, <, >=, <=, !=, etc. These operators are particularly useful in conditional statements (such as @if).
Magnitude Comparison
@if $width > 100
.large-width { width: 120px; }
@endif
When $width is 110, the condition holds true, and the style is applied.
Logical Comparison
@if $isActive && $isVisited
.active { background: #ff0000; }
@endif
The style takes effect only when both conditions are satisfied simultaneously.
Operator Precedence
Sass operator precedence is similar to JavaScript, but the following rules must be observed:
- Parentheses First: Expressions within parentheses are calculated first.
- Multiplication and Division First: × and / have higher precedence than + and -.
- Right to Left: The order of addition and subtraction operations proceeds from right to left.
For example:
$sum = 10 + 20 - 5 × 2
$sum
The calculation sequence is: 5 × 2 = 10 → 10 + 20 = 30 → 30 - 10 = 20.
Practical Examples
In actual development, the correct use of operators can significantly enhance code readability and efficiency. For instance:
- Using addition to calculate element width:
.container { width: $baseWidth + 20px; } - Using comparison operations to judge user status:
@if $isAuthenticated .user-profile { display: block; } @else .user-profile { display: none; }
By mastering Sass operator rules, developers can more flexibly construct complex style logic while improving code maintainability.