Sass Basics: The Function Directive

Please, for the love of God, do not append the unit as a string. This is an extremely bad practice I am trying to eradicate once and for all.

Adding a string to a number in order to give it a unit usually shows a very poor understanding of basic arithmetic. A unit is not just a random string at the end of a number. There are reasons why 5 metres per 5 metres gives you 25 square metres in real life. Sass units do not behave any differently.

To add a unit to a unitless number, either you should add 0 of this unit to the initial number, or multiply it by 1 of this unit. For instance, 42 * 1px or 42 + 0px are two perfectly valid ways to transform 42 into 42px. On the other hand 42 + px is a terrible way of casting the number in a length, because you end up with a string and not an actual number (as long as we stick to Sass data types).

It works exactly the same when you want to make a length (or what else) unitless: you don’t slice the value to keep the numerical part. You divide it by 1 of this unit, for instance 42px / 1px. Same story.

More information about this: