Question

I know you can strip units from numbers in SASS when you know the unit before-hand like this:

$number: 16px;
$without-unit: 16px / 1px;
@warn $without-unit; // 16

But is it possible to strip the unit from a number without knowing what the unit is first?

@function strip-unit($number) {
  // magic code here...
}

@warn strip-unit(16px); // 16
Was it helpful?

Solution

--

UPDATE: You should never actually need to use this function. Sass math is very smart about units, and I have never seen a use-case in which stripping units was a better option than simply using correct math to get what you need. See the Sass issue thread where this has been discussed at length.

It's a clever function, but if you ever feel like using it, there's probably a problem with your math. Don't fall back on this function. Fix your math instead.

--

You need to divide by 1 of the same unit. If you use unit(), you get a string instead of a number, but if you multiply by zero and add 1, you have what you need:

@function strip-units($number) {
  @return $number / ($number * 0 + 1);
}

That works. strip-units(13.48cm) will return 13.48.

OTHER TIPS

I think you'd have to add a custom Ruby function to strip the units (see the documentation on adding custom functions). It would look something like this, I think (warning, untested):

module Sass::Script::Functions
  def strip_units(num)
    assert_type num, :Number
    Sass::Script::Number.new(num.value)
  end
end

The only use case for strip units SASS function is when writing unit conversion functions. I've only found it useful for the task of converting PX to EM/REM and vice versa.

You need to divide by 1 of the same unit. If you use unit(), you get a string instead of a number, but if you multiply by zero and add 1, you have what you need - Miriam Suzanne

I believe SASS compiler treats values very similarly to what PHP interpreter does (with a warning though), so I believe the statement above is incorrect. If you divide or multiply a string (which starts with a number e.g. '16px') with a number value (or a string value that starts with a number), the string is converted to number for the compiler to be able to perform the operation.

Same goes for adding a string to number, it converts the number to a string.

The following solution applies this tactic correctly:

@function strip-unit($value) {
  @return $value / 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top