jiwopene
jiwopene

Reputation: 3627

SASS/SCSS variable not working with CSS variable assignment

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;
}

Upvotes: 5

Views: 2073

Answers (2)

Web Allex
Web Allex

Reputation: 31

I destroyed my brain for 2 hours trying to understand why it dosent work.

  --primary-color: #{map.get($dark-theme-app-var, primary-color)};
  --primary-color: map.get($dark-theme-app-var, primary-color);

and chatGpt did not catch that :). Thank you.

Upvotes: -1

Youssouf Oumar
Youssouf Oumar

Reputation: 45825

It's not a bug, it's how the Sass compiler works regarding 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 behavior, and only doing so works:

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

Upvotes: 8

Related Questions