I wonder if it is possible to have a CSS rule only applied if a css variable is defined. I've seen it is possible to define a default value, something like:
background-color: var(--bgColor, red);
But I don't think this will work in my project, Because what I would like is that when the variable is not defined to get the style that it will have if that line was not there in the CSS.
I added a codepen, to make it easier to understant what I am talking about:
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.
This is not possible even if you use an invalid value.
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
And
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.
So any property using a css variable will be valid whatever its content. It will be invalid only at computed time and will fallback to inherit
or initial
(never to another value specified somewhere else)
See the below example.
html {
background:red;
background:lol-gradient(var(--c), super-power-red-color);
}
The background will not be red and that strange value is valid even if the css variable is not defined and I using a clearly invalid value.