15

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?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
swift-lynx
  • 3,219
  • 3
  • 26
  • 45

1 Answers1

34

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

.text {
    color: blue;
    color: var(--tintColor, blue);
}
<div class="text">some text here</div>
<div class="text" style="--tintColor: red">some text here</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • 3
    this line `color: blue;` is redunant in 2k20 :3 – vovchisko Nov 19 '20 at 16:47
  • @vovchisko Good point, but it may be useful to keep it for some HTML to PDF conversion tools that aren't always up to date with the latest CSS modules. Typically, [it seems that wkhtmltopdf was handling it and no longer now, probably by error](https://github.com/wkhtmltopdf/wkhtmltopdf/issues/4827). – Patrick Janser Aug 09 '23 at 14:24