简体   繁体   English

如何在 scss 文件中使用 css 全局变量?

[英]How to use css global variables in scss file?

I am gonna use css global variables in scss file so that I can change the button colour in any time.我将在 scss 文件中使用 css 全局变量,以便随时更改按钮颜色。

I want to do like this:我想这样做:

:root {
--button-color: #FF0000;
}

$button-color: var(--button-color);

...

But this makes the issue now.但这成为了现在的问题。

SASS variables are compile time and final value depends on all files were @import in line. SASS 变量是编译时间,最终值取决于所有文件都是@import行。 CSS variables are run-time and are calculated based on cascade(say if any parent element redeclares variable - it will be applied to children). CSS 变量是运行时变量,并且基于级联计算(例如,如果任何父元素重新声明变量 - 它将应用于子元素)。

Also take a look into docs section on difference between另请查看有关两者之间差异的文档部分

You can use css-vars to compile SASS variables into CSS custom properties.您可以使用css-vars将 SASS 变量编译成 CSS 自定义属性。 But you still cannot use CSS custom properties in SASS code, say, to calculate some value - since CSS property is not initialized yet.但是您仍然不能在 SASS 代码中使用 CSS 自定义属性来计算某个值 - 因为 CSS 属性尚未初始化。

Even with css-vars plugins, things are rather messy, because SASS files does not describe how component tree looks like finally so we cannot see cascade.即使使用css-vars插件,事情也相当混乱,因为 SASS 文件没有描述组件树最终的样子,所以我们看不到级联。

TL;DR; TL;博士; don't mix SASS variables and CSS custom properties.不要混合 SASS 变量和 CSS 自定义属性。 Use first for compile-time variables/calculation only and use latest one for run-time/cascade-based styling. first 仅用于编译时变量/计算,并将最新的用于运行时/基于级联的样式。 Probably prefer using CSS custom properties only.可能更喜欢仅使用 CSS 自定义属性。

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

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