skip to Main Content

Please see the code snippet below. I’m looking for a way to set a value for --foo such that the button keeps its originally-defined color, red.

:root {
  --foo: ;
}

button {
  background: red;
  
  /**
   * Is there a way to set a value for `--foo` such that
   * this rule does not override the `background: red` rule
   * above?
   */
  background: var(--foo);
}
<button>Launch</button>

2

Answers


  1. Use an unset --foo and provide a fallback value – the first rule can actually be replace with the second for smaller CSS even

    Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/var#syntax

    :root {
      --foo;
    }
    
    button {
      /*
       * Is there a way to set a value for `--foo` such that
       * this rule does not override the `background: red` rule
       * above?
       */
      background-color: var(--foo, red);
    }
    <button>Launch</button>

    Alternate option THIS is probably what you actually meant since that initial might be anywhere prior:

    :root {
      --foo;
    }
    
    button {
      background-color: red;
      /* initial value of the property as fallback */
      var(--foo, initial);
    }
    <button>Launch</button>
    Login or Signup to reply.
  2. This code sets –foo to its initial value, which will not affect the background property for the button element, and the background: red; rule will take precedence.

    :root {
      --foo: initial;
    }
    
    button {
      background: red;
      background: var(--foo);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search