Developer123 Developer123 - 15 days ago 7
Sass (Sass) Question

Sass divide does not work when using with sass function

I have this function that converts px to em:

@function em($pixels, $context: 16px) {
@return #($pixles/$context)em
}


I have variable that uses this function:

$margin: em(60px);


Now I am trying to use it like this:

div {
margin: 0 -#{$margin / 2};
}


But this is invalid css. the output in the devtools is:

margin: 0 -3.75em / 2


When I removing the function and just use em value it's working.
How can I do this?

Answer

First of all, I think there is a typo in your function code but I am ignoring that because your function is working fine based on your output. The real problem is with the type of value that is being output by the function. Since you are just concatenating the em to the calculated value using interpolation, the output is a string and not a number, so you cannot perform math operations on it.

Instead of concatenating the em, use multiplication by 1em to append the units and now your original code would work fine.

@function em($pixels, $context: 16px) {
  @return ($pixels/$context) * 1em;
}