Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS variable with fallback value of itself

What I'm trying to achieve in javascript will look like this:

myVar = newVar || myVar;

In css I'm doing the following:

--my-var: var(--new-var, var(--my-var))

Seems like it does not work. Is it even possible to have an old value in fallback if new value is undefined?

like image 320
ZuzEL Avatar asked Oct 23 '25 14:10

ZuzEL


2 Answers

Generally CSS can't do if/then/else, but when using i.e. var one can, kind of.

Using var() you can define a fallback value when the given variable is not yet defined

The second (optional) argument, the declaration-value, has some limits though.

The production matches any sequence of one or more tokens. So, as long as the sequence does not contain , , unmatched <)-token>, <]-token>, or <}-token>, or top-level tokens or tokens with a value of "!" ,it represents the entirety of what a valid declaration can have as its value.

Src:

  • MDN CSS Var
  • MDN Using CSS variables

This won't work

:root{ 
  --myOld: lime;
  --myVar: var(--myNew, --myOld) 
}

div {
  color: var(--myVar)
}
<div>Hey there</div>

This will work

:root{ 
  --myOld: lime;
  --myVar: var(--myNew, var(--myOld)) 
}

div {
  color: var(--myVar)
}
<div>Hey there</div>

And this will work

:root{ 
  --myVar: var(--myNew, var(--myOld, red)) 
}

div {
  color: var(--myVar)
}
<div>Hey there</div>

For javascript, doing like that you get a reference error, and to avoid that you can do like this:

myVar = (typeof newVar === 'undefined') ? myVar : newVar;

Src: Why does an undefined variable in Javascript sometimes evaluate to false and sometimes throw an uncaught ReferenceError?

like image 176
Asons Avatar answered Oct 26 '25 03:10

Asons


You can't assign the value of a custom property as a fallback value in a var() expression when redeclaring the same custom property. The old value is overridden during cascade resolution, so there would be no old value left to fall back to by the time the var() expression is evaluated.

like image 44
BoltClock Avatar answered Oct 26 '25 04:10

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!