Search code examples
htmlcsscss-variables

How to use CSS Variables only when they exist?


I have some CSS where I want a default color and then override it with a variable. When the CSS Variable doesn't exist, I want to use the fallback color.

:root {
    /*--tintColor: red;*/
}

.text {
    color: blue;
    color: var(--tintColor);
}

When the variable isn't set like if its commented out the color becomes black. I want it in this case that the color falls back to the blue when the variable isn't defined. Is this possible?


Solution

  • You can specify the fallback property like var(--tintColor, blue) - see demo below:

    .text {
        color: var(--tintColor, blue);
    }
    <div class="text">some text here</div>
    <div class="text" style="--tintColor: red">some text here</div>