How do I multiply two percentages together in Sass, in a sensible way?
For example, consider the following declarations:
$num1: 50%;
$num2: 25%;
$num3: $num2 * $num1;
Here, num3
breaks. What expression can I write to have num3
defined as 12.5%
?
Unlike other mathematical operations, division in Sass is done with the math. div() function. Although many programming languages use / as a division operator, in CSS / is used as a separator (as in font: 15px/32px or hsl(120 100% 50% / 0.8) ).
Percentages in Sass work just like every other unit. They are not interchangeable with decimals, because in CSS decimals and percentages mean different things. For example, 50% is a number with % as its unit, and Sass considers it different than the number 0.5 .
SASS allows for mathematical operations such as addition, subtraction, multiplication and division. You cannot use incompatible units such as px * px or while adding number with px and em leads to produce invalid CSS. Therefore, SASS will display an error if you use invalid units in CSS.
Figured it out; first you need to convert one of the percentages to a decimal. Here's how it's done:
$num1: 50%;
$num2: 25%;
$num3: ($num2/100%) * $num1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With