Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass @if true statement not working function

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?

like image 858
McShaman Avatar asked Jun 17 '13 21:06

McShaman


2 Answers

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;
    }
    ...
}
like image 135
Ye Liu Avatar answered Oct 10 '22 13:10

Ye Liu


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

like image 21
cimmanon Avatar answered Oct 10 '22 13:10

cimmanon