Strip-unit Function

Avatar of Kitty Giraudel
Kitty Giraudel on

There is a lot of confusion around the way units work in Sass. Yet, they work exactly as they do in real life. If you want to remove the unit of value, you have to divide it by 1 unit. For instance, to remove the cm unit of 42cm, you have to divide it by 1cm. It works exactly the same in Sass.

$length: 42px;
$value: $length / 1px;
// -> 42

But what if you don’t know the unit in use? Let’s say it could be anything, from pixels to em or even vw and ch. Then we need to abstract the logic in a function:

/// Remove the unit of a length
/// @param {Number} $number - Number to remove unit from
/// @return {Number} - Unitless number
@function strip-unit($number) {
  @if type-of($number) == 'number' and not unitless($number) {
    @return $number / ($number * 0 + 1);

  @return $number;

The calculation might look odd but it actually makes sense. In order to have 1 of the unit of $number, we can multiply $number by 0 and then add 1.


$length: 42px;
$value: strip-unit($length);
// -> 42