2

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>
user2923322
  • 1,072
  • 1
  • 11
  • 25
  • 3
    You are trying to override the variable with itself, which is not going to work. You could perhaps define a `--fallback-bg` value instead? `background-color: var(--background-color, var(--fallback-bg));` – chriskirknielsen Mar 16 '20 at 13:57
  • @chriskirknielsen Actually I like your approach. You can make an answer, and I will accept it. Thank you. – user2923322 Mar 16 '20 at 14:01
  • Sure thing! Glad to help. – chriskirknielsen Mar 16 '20 at 14:13
  • The first duplicate will give you the *why* and here another related question giving almost the same idea as the answer below: https://stackoverflow.com/a/60660908/8620333 (the JS is irrelevant) – Temani Afif Mar 16 '20 at 14:41

1 Answers1

5

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));

chriskirknielsen
  • 2,839
  • 2
  • 14
  • 24