gpt4 book ai didi

CSS 变量默认为 : set if not already set

转载 作者:行者123 更新时间:2023-12-02 07:59:45 28 4
gpt4 key购买 nike

我的 Web 组件使用 CSS 变量。

这些变量需要默认值。

它们在许多文件中使用,所以我想提供一次默认值,而且只提供一次。

第一次尝试使文本变黑。为什么?

一次提供默认值的正确方法是什么?

.a {
--my-variable: red;
}

.b {
--my-variable: var(--my-variable, blue);
}
<div class="a">
<div class="b">
<span style="color: var(--my-variable);">text</span>
</div>
</div>

最佳答案

This first attempt makes the text black. Why?


因为这个 --my-variable: var(--my-variable, blue);无效,因为您试图用自身表达相同的变量,这是不允许的,因此浏览器将简单地忽略它。然后在使用 color: var(--my-variable); 时颜色将回退到 initial值为黑色。
正确的方法是简单地在上层定义变量,它会被所有元素继承(就像@kornieff 提供的解决方案)

来自 the specification :

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.

For each element, create a directed dependency graph, containing nodes for each custom property. If the value of a custom property prop contains a var() function referring to the property var (including in the fallback argument of var()), add an edge between prop and the var. Edges are possible from a custom property to itself. If there is a cycle in the dependency graph, all the custom properties in the cycle must compute to their initial value (which is a guaranteed-invalid value).

关于CSS 变量默认为 : set if not already set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015022/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com