CSS variable with fallback value of itself

旧巷老猫 提交于 2019-12-02 07:32:20

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.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!