Search code examples
csscss-variables

Inherit a CSS variable, or fallback to default


Say I am a library author of some web component; I want to allow the user to set the background color of my component. I allow this by setting --background-color. For example, the user can code:

:root {
  --background-color: green;
}

Now in my component, I want to either take the user's value for --background-color, or use a default color:

.some-component {
  display: contents;
  --background-color: var(--background-color, red);
}

The code above however doesn't work. I don't mind, there are workarounds; but I would like to know why it doesn't work, if anyone has an answer for that.

In the code below, green is expected, but the line --background-color: var(--background-color, red); seems to "break" somehow the CSS.

:root {
  --background-color: green;
}
.some-component {
  display: contents;
  --background-color: var(--background-color, red); /* this doesn't work */
}
.some-component__container {
  background-color: var(--background-color, blue);
  height: 100px;
  width: 100px;
}
<!-- user code -->
<div class="app">
  <!-- library code -->
  <div class="some-component">
    <div class="some-component__container">
    </div>
  </div>
</div>


Solution

  • You can't override a variable with itself, so what I can suggest is to define a second variable that will contain your fallback value for each context:

    :root {
      --fallback-bg: green;
    }
    .some-component {
      display: contents;
      --fallback-bg: red;
    }
    .some-component__container {
      background-color: var(--background-color, var(--fallback-bg));
      height: 100px;
      width: 100px;
    }
    

    You can also define a fallback for your fallback if you'd like: background-color: var(--background-color, var(--fallback-bg, green));