CSS变量-交换值?
问题描述:
我有一个非常简单的CSS变量问题.我想交换两个CSS变量,基本上是ES6中[a, b] = [b, a]
的CSS等效项.这是一个简单的示例:
I have a very simple problem with CSS variables. I would like to swap two CSS variables, basically the CSS equivalent of [a, b] = [b, a]
in ES6. Here's a simple example:
<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()
是实时绑定.我在这里想念什么吗?还是这是规范当前的工作方式?
However, this fails because CSS var()
s are live bindings. Am I missing something here? Or is this the way the spec currently works?
答
您正在创建循环依赖项,因为您正在使用另一个属性来定义每个属性,因此这是行不通的.相反,您可以通过引入更多变量来尝试类似的操作:
You are creating a cyclic dependence because you are defining each property using the other one and this won't work. Instead you may try something like this by introducing more variables:
: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>