如果包含未声明的 CSS 变量,是否应该显示 CSS 内容?

Is CSS content supposed to be shown if it includes an undeclared CSS variable?

以下 CSS 代码将根据是否定义变量 --test2 生成不同的结果:

html::before {
    content: "test1:" var(--test1) " test2:" var(--test2);
}

如果定义了--test1--test2,测试内容将显示在视口中。如果定义了 --test1--test2 未定义 ,则 none显示测试内容

这是正确的行为吗?如果是,为什么?

来自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, respectively, as if the property’s value had been specified as the unset keyword.

在你的例子中,你没有定义变量,所以它有 initial 作为值,这将使 content 回退到它的初始值(即 none)所以什么都不会显示。


来自相同的规范:

When a custom property has its initial value, var() functions cannot use it for substitution. Attempting to do so makes the declaration invalid at computed-value time, unless a valid fallback is specified.

所以最好考虑后备方案:

html::before {
    content: "test1:" var(--test1,"") " test2:" var(--test2,"");
}