CSS变量默认值:如果尚未设置,则设置 [英] CSS variables defaults: set if not already set
问题描述
我的Web组件使用CSS变量.
My Web Component uses CSS variables.
这些变量需要默认值.
它们在许多文件中都使用过,因此我想一次提供默认值,一次仅提供一次.
They are used in many files, so I want to provide the defaults once, and only once.
第一次尝试使文本变黑.为什么?
This first attempt makes the text black. Why?
一次提供默认值的正确方法是什么?
What is the correct way to provide the defaults once?
.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
值为黑色的值.
Because this --my-variable: var(--my-variable, blue);
is invalid as you are trying to express the same variable with itself which is not allowed so the browser will simply ignore it. Then later when using color: var(--my-variable);
the color will fallback to the initial
value which is black.
正确的方法是简单地在较高级别上定义变量,它将被所有元素继承(例如@kornieff提供的解决方案)
The correct way is to simply define the variable on an upper level and it will get inherited by all the element (like the solution provided by @kornieff)
来自规范:
几乎不对自定义属性进行评估,只是它们允许并评估var()函数的值.这可以创建循环依赖项,其中自定义属性使用var()对其进行引用,或者两个或两个以上的自定义属性分别尝试相互引用.
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.
为每个元素创建一个有向依存关系图,其中包含每个自定义属性的节点.如果自定义属性prop的值包含引用属性var的var()函数(包括在var()的后备参数中),请在prop和var之间添加一条边.从自定义属性到自身,边缘都是可能的.如果相关性图中有一个循环,则循环中的所有自定义属性都必须计算为其初始值(这是保证无效的值).
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变量默认值:如果尚未设置,则设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!