gpt4 book ai didi

css - 是否可以检查是否定义了 CSS 变量?

转载 作者:行者123 更新时间:2023-12-04 14:05:55 25 4
gpt4 key购买 nike

我想知道是否可以仅在定义了 css 变量时才应用 CSS 规则。我已经看到可以定义一个默认值,例如:

background-color: var(--bgColor, red);
但我认为这不会在我的元素中起作用,因为我想要的是,当 undefined variable 以获取如果 CSS 中没有该行时它将具有的样式。
我添加了一个代码笔,以便更容易理解我在说什么:
https://codepen.io/xmorelll/pen/bGWLoaL

.container {
margin: 5px;
}
.content {
padding: 5px;
display: inline-block;
height: 100px;
width: 100px;
border: 1px solid black;
background-color: var(--bgColor) !important;
}
<div class="container">
<div class="content" style="background-color: blue">blue</div>
</div>

<div class="container">
<div class="content" style="background-color: yellow">yellow</div>
</div>

<div class="container" style="--bgColor: red">
<div class="content" style="background-color: green">red</div>
</div>

<div class="container">
<div class="content" style="--bgColor: green">green</div>
</div>

最佳答案

Because what I would like is that when the variable is not define to get the style that it will have if that line was not there in the CSS.


即使您使用无效值,这也是不可能的。
来自 the specification

A declaration can be invalid at computed-value time if it contains a var() that references a custom property with its initial value, as explained above, or if it uses a valid custom property, but the property value, after substituting its var() functions, is invalid. When this happens, the computed value of the property is either the property’s inherited value or its initial value depending on whether the property is inherited or not



If a property contains one or more var() functions, and those functions are syntactically valid, the entire property’s grammar must be assumed to be valid at parse time. It is only syntax-checked at computed-value time, after var() functions have been substituted.


因此,任何使用 css 变量的属性都将是有效的,无论其内容如何。仅在计算时无效,并回退到 inheritinitial (永远不会到其他地方指定的另一个值)
请参阅以下示例。

html {
background:red;
background:lol-gradient(var(--c), super-power-red-color);
}

背景不会是红色的,即使未定义 css 变量并且我使用了明显无效的值,该奇怪的值也是有效的。
enter image description here

关于css - 是否可以检查是否定义了 CSS 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68546715/

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