css - 解释这个 CSS 自定义属性行为

标签 css css-variables

<分区>

我很难理解以下 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并对此进行了调查。

关于css - 解释这个 CSS 自定义属性行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62540386/

相关文章:

html - 在其他图片上叠加和复制图片

css - 将变量从 SASS 导出到 vanilla CSS?

css - 是否可以在 css "background url"中使用 css 变量

javascript - 通过 JavaScript 访问 CSS 自定义属性(又名 CSS 变量)

css - Lessphp 对比函数的输出与文档不匹配

javascript - 使用 JavaScript 根据页面宽度更改 CSS 样式

css - 如何用我自己的图标替换任务栏股票图标浏览器

html - 无法使用 css、html 在正确的位置对齐 div

具有自身后备值的 CSS 变量

CSS使用另一个类的颜色?