4

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?

2 Answers 2

7

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:

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?

Sign up to request clarification or add additional context in comments.

1 Comment

@ZuzEL That is perfectly fine
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.