Search code examples
csssasscss-variables

CSS variables and SASS functions


We know the advantages of using CSS4 variables but what if we need to get these values from a SASS function like so?:

:root {
    --gap-l: toRem(10);
}

toRem is a Sass function that I call to get the sizes dynamically:

$fontSize: 16;
@function toRem($val) {
    @return $val / $fontSize * 1.6 + 0rem;
}

This won't fail but won't work either. To have this working we can just have the value directly on --gap-l or keep using SASS vars.

If I try something like --gap-l: #{toRem(10)};

The error I encounter is that it doesn't call the SASS function:

enter image description here


Solution

  • Try this --gap-l: #{toRem(10)};, the #{} syntax is called interpolation. In the experience of heading bugs myself, when you want to use a SASS expression's raw value along with normal CSS, if you can't use the concise syntax like just toRem(10), try adding interpolation to see if it works. Another example:

    $padding: 5px;
    .element {
      width: calc(100% - $padding); // will not work, it must be:
      width: calc(100% - #{$padding});
    }
    

    Here is the code with the updated question: https://jsfiddle.net/bcw763en/. Notice that if you put :root above the @function, it'll not work.