6

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

2 Answers 2

10

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
}
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
The question was already answered and accepted. What new or different information was your answer meant to bring compared to existing answer? To me, your answer looks just the same but far less explained and sourced, so useless...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.