Search code examples
csscss-variables

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?


Solution

  • 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?