How do you remove units from the Sass mix equation?

I wrote a very simple Sass mixin to convert pixel values ​​to rem values ​​(see Jonathan Snook 's article on the benefits of using blogs ). Here is 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 pretty well, but I'm a little unsatisfied with the include syntax. See, I would rather pass the pixel value to the include statement instead of a prime number. This is a small detail, but it will add semantic meaning to the include statement, which does not currently exist. Here is what I get when I try to pass a pixel value to an include statement:

 // Include syntax p { @include rem(font-size,14px); } // Rendered CSS p { font-size: 14pxpx; font-size: 1.4pxrem; } 

As soon as Sass sees that the pixel value is passed into the equation, it produces "px". I want to remove this unit of measure as if I were using parseFloat or parseInt in JavaScript. How to do this inside a Sass mix?

+6
source share
2 answers

Removing units from a number is done by division, as 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 interpreted as in real mathematics, so px / px / rem goes into just rem. Enjoy it!

+7
source

Here is a function you can use. Based on foundation of global helper functions.

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

Using an example:

 ... Removed for brevity ... @mixin rem( $key: font-size, $val ) { #{$key}: strip-unit( $val ) * 1px; #{$key}: ( strip-unit( $val ) / $base-font-size ) * 1rem; } 
+8
source

Source: https://habr.com/ru/post/894192/


All Articles