Correctly Adding Unit to Number

0
0

When converting a unitless number to a length, duration, angle or whatever, people tend to simply append the unit as a string, like this:

$value: 42;
$length: $value + px;
// 42px

While this method works, it is far from ideal because it results in implicitly casting the initial value as a string. Indeed, if you try doing math with the $length value from now on, you’ll see that Sass quickly throws an error because it cannot do math operators with a string.

To work around this issue, there are two ways of doing this properly:

$value: 42;
$length: $value + 0px;
// 42px
$value: 42;
$length: $value * 1px;
// 42px

Any of those methods will correctly produce a number as expected and not a string.

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.