Search code examples
htmlcsssasscompass-sass

Invalid operands for multiplication when piping two SCSS functions


I'm working on SASS unit-conversion function, and i have defined two functions:

convert-units(...);
strip-units(...);

Both work perfectly fine separately, until i pipe one in another, like this:

strip-units( convert-units(...) );

the result is following error:

invalid operands for multiplication on line 68 at column 23

I tried to copy manually result from convert-units() into strip-units(), and it it works correctly.

Here is the working example: http://sassmeister.com/gist/b5c61fc7baec1e3bec1f Please scroll to the bottom until you find commented pipe: strip-units(... fragment.

Any help would be appreciated.


Solution

  • This is because the line $pxValue / $size + $outputUnit actually does not create a number with a unit, but a string which looks exactly the same. There is no easy way to add a unit to a number in sass, but I found an answer in this question (there's also a little bit more background about why there is no easy way):

    @function length($number, $unit) {
      $strings: 'px' 'cm' 'mm' '%' 'ch' 'pica' 'in' 'em' 'rem' 'pt' 'pc' 'ex' 'vw' 'vh' 'vmin' 'vmax';
      $units:   1px  1cm  1mm  1%  1ch  1pica  1in  1em  1rem  1pt  1pc  1ex  1vw  1vh  1vmin  1vmax;
      $index: index($strings, $unit);
    
      @if not $index {
        @warn "Unknown unit `#{$unit}`.";
        @return false;
      }
    
      @return $number * nth($units, $index);
    }
    

    Then simply do $outputValue: length($pxValue / $size, $outputUnit); and it works.

    See my gist (I failed to make SassMeister save my updated code, don't know why)