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

Is it possible to check if a CSS variable is defined or not?

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

background-color: var(--bgColor, red);

但我认为这在我的项目中行不通,因为我想要的是,当变量未定义时,如果该行不在 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>

您不能在变量中设置默认值但是,
您可以为默认值定义相同的键,然后为变量值定义相同的键

:root {
  --bg: pink;
}

div {
  background-color: red;  /*Default value*/
  background-color: var(--bg);
}
<div> 123</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 变量并且我使用了一个明显无效的值,背景也不会是红色的并且那个奇怪的值是有效的。