我很难理解以下 CSS 变量,我相信代码不言自明,否则请告诉我。
:root {
--color: red;
--hover-color: var(--color);
}
div {
--color: green;
background: var(--color);
}
div:hover {
background: var(--hover-color);
}
<div>
Why am I red on hover? Shouldn't I be green? When inspecting this element on hover, chrome shows the green color!?
</div>
让我非常困惑的是,在 Chrome Devtools 中检查元素时,它显示悬停颜色为绿色??
--hover-color
解析为它所在范围的 --color
值,这意味着它将计算当时检测到的值。这是为了避免依赖循环。您可以阅读有关 these cycles in the specification document 的信息.
Custom properties are left almost entirely unevaluated, except that they allow and evaluate the var()
function in their value. This can create cyclic dependencies where a custom property uses a var()
referring to itself, or two or more custom properties each attempt to refer to each other.
为防止这种情况发生,您需要扩展一点,然后执行以下操作:
:root {
--color: red;
--hover-color: var(--color);
}
div {
--color: green;
--hover-color: var(--color); /* Added this here */
background: var(--color);
}
div:hover {
background: var(--hover-color);
}
<div>
I am green on hover, as expected.
</div>
但这会引发 Chrome 开发工具的一个有趣问题,它确实会在悬停状态的背景值旁边显示绿色预览。你可能想要 file an issue并对此进行了调查。