CSS 变量 - 交换值?

CSS Variables - Swapping values?

我有一个关于 CSS 变量的非常简单的问题。我想交换两个 CSS 变量,基本上是 ES6 中 [a, b] = [b, a] 的 CSS 等价物。这是一个简单的例子:

<p>White background</p>
<button>Black background</button>
<div>
  <p>Black background</p>
  <button>White background</button>
</div>
:root {
  --primary-color: #fff;
  --secondary-color: #000;
}

body {
  background-color: var(--primary-color);
}

button {
  background-color: var(--secondary-color);
}

div {
  /* i'd like to do the following: */
  --primary-color: var(--secondary-color);
  --secondary-color: var(--primary-color);

  /* so here, `--primary-color` would be `--secondary-color` from `:root`
   * and any children have these colors swapped as well
   */
  background-color: var(--primary-color);
}

但是,这失败了,因为 CSS var() 是实时绑定。我在这里错过了什么吗?或者这是规范当前的工作方式?

您正在创建循环依赖,因为您使用另一个 属性 来定义每个,这是行不通的。相反,您可以通过引入更多变量来尝试这样的事情:

:root {
  --p:#fff;
  --s:#000;
  --primary-color: var(--p);
  --secondary-color: var(--s);
}

body {
  background-color: var(--primary-color);
}

button {
  background-color: var(--secondary-color);
}

div {
  /* i'd like to do the following: */
  --primary-color: var(--s);
  --secondary-color: var(--p);
  
  background-color: var(--primary-color);
}
<p>White background</p>
<button>Black background</button>
<div>
  <p>Black background</p>
  <button>White background</button>
</div>