Correctly Adding Unit to Number

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.

Reference URL

Comments

  1. User Avatar
    M.Ali
    Permalink to comment#

    I use the last method, and it works fine.

  2. User Avatar
    Linus Miller

    Multiplication is a far more complicated operation for a computer to do that addition. So always use the first one.

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag