1

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)}; this is the error I get: enter image description here

It doesn't call the SASS function

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Dani
  • 3,128
  • 2
  • 43
  • 91
  • There is nothing called "CSS4 variables", that's why I edited the question to make it "CSS variables" which is the correct term. – Temani Afif Dec 17 '19 at 19:45
  • I always understood that was CSS4 variables: https://codepen.io/jakealbaugh/post/css4-variables-and-sass or https://github.com/ionic-team/ionic/issues/14801 – Dani Dec 17 '19 at 22:28
  • those links are using wrong temrs. you will find noting about CSS4 variables in any official specification. Even CSS4 as term doesn't exist, check this: https://stackoverflow.com/a/54055521/8620333 – Temani Afif Dec 17 '19 at 22:35
  • Ok, so it might be a misunderstanding about these terms on the internet then. Thanks for the clarification – Dani Dec 17 '19 at 23:14

2 Answers2

3

You can definitely do that: what you're missing is simply using string interpolation, i.e.:

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

The reason is highlighted in their "breaking changes" documentation with regards to CSS variables:

To provide maximum compatibility with plain CSS, more recent versions of Sass require SassScript expressions in custom property values to be written within interpolation. Interpolation will also work for older Sass versions, and so is recommended for all stylesheets.

Terry
  • 63,248
  • 15
  • 96
  • 118
1

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.

Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52