Append unit type to the result of a calculation in Sass
The only way to add a unit to a number is via arithmetic.
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
You can try either of these:
font-size: $size * 1px;
or
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
Choose the method you prefer
$font: 24px;
$base: 16px;
No variables
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
.item2 { font-size: #{$font / $base}em; }
One variable
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}