I am trying to make a function which converts a pixel size to ems or rems. The function is as follows:
@function px2em($pixels, $fontSize: 16, $rem: false) {
@if $rem == true {
$unit: 0rem;
} @else {
$unit: 0em;
}
$ratio: 1 / $fontSize;
@return ($pixels * $ratio) + $unit;
}
When I compile this I get the following error:
error style.scss (Line 36 of _functions.scss: Undefined variable: "$unit".)
What am I doing wrong here?
SASS has block scope
, variables defined in one block will only be available in that scope. So you want to use $unit outside of the if-else block, so you should declare it like this:
@function px2em($pixels, $fontSize: 16, $rem: false) {
$unit: 0em;
@if $rem == true {
$unit: 0rem;
}
...
}
In this particular instance, you may want to use the if()
function, rather than an @if
statement
$unit: if($rem, 0rem, 0em);
http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#if-instance_method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With