SASS/SCSS variable not working with CSS variable assignment

Issue

I have the following SCSS code:

@mixin foo($bar: 42) {
    --xyzzy: $bar;
}
bar {
    @include foo;
}

I would expect that I get CSS variable --xyzzy set to 42 on all bar elements. Instead of this, I get CSS stating bar { --xyzzy: $bar; }. The variable was not interpreted. I would need to use #{…} syntax instead to get the variable set.

Is this a feature of the SCSS/SASS? A bug? Can I get the interpretation working without enclosing the variable name in #{…}?

Actual result:

bar {
  --xyzzy: $bar;
}

Expected:

bar {
  --xyzzy: 42;
}

Solution

It’s not a bug, it’s how Sass complier works when it comes to CSS custom properties, known as CSS variables. The syntax #{…} is called interpolation and it is the only way to inject dynamic values into a custom property. Here is a quote from the doc:

CSS custom properties, also known as CSS variables, have an unusual declaration syntax: they allow almost any text at all in their declaration values. What’s more, those values are accessible to JavaScript, so any value might potentially be relevant to the user. This includes values that would normally be parsed as SassScript.

Because of this, Sass parses custom property declarations differently than other property declarations. All tokens, including those that look like SassScript, are passed through to CSS as-is. The only exception is interpolation, which is the only way to inject dynamic values into a custom property.

That’s the reason why you have that behaviour, and only doing so works:

@mixin foo($bar: 42) {
   --xyzzy: $bar;    // does not work
   --xyzzy: #{$bar}; // works
}

Answered By – yousoumar

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.