CSS 中的变量 - 为什么不能使用它们?

Variables in CSS - why can't they be used?

这让我困扰了一段时间,我在任何地方都找不到答案:为什么 不纯 CSS 允许我们使用变量?

我们都知道 SASS 和 LESS 预处理器让我们的生活变得如此轻松 - 例如让我们使用变量。为什么 W3C 还没有在 CSS 本身中实现这样的功能有什么特别的原因吗?

我想所有开发人员(包括来自 W3C 的开发人员)都会同意这将是向前迈出的一大步。有没有什么特别的原因(还没有)?

好吧,有一个叫做自定义属性的规范 https://www.w3.org/TR/css-variables-1/

但支持现在有点问题..但它在那里.. http://caniuse.com/css-variables/embed

你 can/should 从 css 变量开始 https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables

总结我的研究:

您不必使用 SASS 或 LESS 来利用 CSS 中的变量。

要在 CSS 中设置一些可重复使用的值,您必须使用自定义 属性 表示法声明它们,例如--main-color: black;

然后您可以使用 var() 函数在样式文件中的任何位置访问它们,例如color: var(--main-color);

下面的工作示例:

:root {
  --main-theme-color: red;
}

.one {
  background-color: var(--main-theme-color);
  margin: 10px;
  width: 50px;
  height: 50px;
}

.two {
  background-color: var(--main-theme-color);
  margin: 10px;
  width: 50px;
  height: 50px;
}
.three {
  background-color: var(--main-theme-color);
  margin: 10px;
  width: 50px;
  height: 50px;
}
.four {
  background-color: black;
  color: var(--main-theme-color);
  margin: 10px;
  width: 50px;
  height: 50px;
}
<div class="one"> </div>
<div class="two"> </div>
<div class="three"> </div>
<div class="four"> RED </div>