开发者

How do you remove units of measurement from a Sass mixin equation?

I've written a very simple Sass mixin for converting pixel values into rem values (see Jonathan Snook's article on the benefits of using rems). Here's the code:

// Mixin Code
$base_font_size: 10; // 10px
@mixin rem($key,$px) {
  #{$key}: #{$px}px;
  #{$key}: #{$px/$base_font_size}rem;
}

// Include syntax
p {
  @include rem(font-size,14);
}

// Rendered CSS
p {
  font-size: 14px;
  font-size: 1.4rem;
}

This mixin works quite well, but I'm a bit unsatisfied with the include syntax for it. See, I would much rather pass a pixel value into the include statement instead of a simple number. This is a small detail, but it would add semantic meaning to the include statement that currently doesn't开发者_如何学C exist. Here's what I get when I try to pass a pixel value into the include statement:

// Include syntax
p {
  @include rem(font-size,14px);
}

// Rendered CSS
p {
  font-size: 14pxpx;
  font-size: 1.4pxrem;
}

Once Sass sees a pixel value being passed into an equation, it outputs the 'px'. I want to strip that unit of measure out as if I were using parseFloat or parseInt in JavaScript. How does one do so inside of a Sass mixin?


Here is a function you could use. Based of Foundation global helper functions.

@function strip-unit($num) {

  @return $num / ($num * 0 + 1);
}

Sample use:

... Removed for brevity ...

@mixin rem( $key: font-size, $val ) {
    #{$key}: strip-unit( $val ) * 1px;
    #{$key}: ( strip-unit( $val ) / $base-font-size ) * 1rem;
}


Removing units from a number is done by division, just like in Algebra.

$base-font-size: 10px;
$rem-ratio: $base-font-size / 1rem;

@mixin rem($key,$px) {
  #{$key}: $px;
  #{$key}: $px/$rem-ratio;
}


// Include syntax
p {
  @include rem(font-size,14px);
}

// Rendered CSS
p {
  font-size: 14px;
  font-size: 1.4rem;
}

Units in Sass can be treated as in real math, so px/px/rem goes to just rem. Enjoy it!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜