简体   繁体   English

SASS/SCSS 变量不适用于 CSS 变量赋值

[英]SASS/SCSS variable not working with CSS variable assignment

I have the following SCSS code:我有以下 SCSS 代码:

@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.我希望我在所有bar元素上将 CSS 变量--xyzzy设置为42 Instead of this, I get CSS stating bar { --xyzzy: $bar; }而不是这个,我得到 CSS 声明bar { --xyzzy: $bar; } bar { --xyzzy: $bar; } . 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?这是 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;
}

It's not a bug, it's how Sass complier works when it comes to CSS custom properties, known as CSS variables.这不是错误,它是 Sass 编译器在 CSS 自定义属性(称为 CSS 变量)时的工作方式。 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. CSS 自定义属性,也称为 CSS 变量,有一种不同寻常的声明语法:它们的声明值中几乎可以包含任何文本。 What's more, those values are accessible to JavaScript, so any value might potentially be relevant to the user.更重要的是,这些值可供 JavaScript 访问,因此任何值都可能与用户相关。 This includes values that would normally be parsed as SassScript.这包括通常会被解析为 SassScript 的值。

Because of this, Sass parses custom property declarations differently than other property declarations.因此,Sass 对自定义属性声明的解析不同于其他属性声明。 All tokens, including those that look like SassScript, are passed through to CSS as-is.所有标记,包括那些看起来像 SassScript 的标记,都按原样传递给 CSS。 The only exception is interpolation , which is the only way to inject dynamic values into a custom property.唯一的例外是interpolation ,这是将动态值注入自定义属性的唯一方法。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM