Search code examples
csscss-variablescss-content

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


The following CSS code will generate different results depending on whether or not variable --test2 is defined:

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

If --test1 and --test2 are defined, the test content will be displayed within the viewport. If --test1 is defined but --test2 is not defined, none of the test content is displayed.

Is this the correct behavior, and if so, why?


Solution

  • From 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.

    In your case, you didn't define the variable so it has initial as value which will make content fallback to its initial value too (which is none) so nothing will show.


    From the same Specification:

    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.

    So better consider a fallback:

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