How do you strip the unit from any number in SASS?

旧时模样 提交于 2019-11-27 11:53:46

--

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!