Search code examples
htmlcsscss-variables

Unset/Delete a custom property/CSS variable


Take the following example:

.article, .note {
    color: var(--text-color, red);
 }
 .theme {
    --text-color: blue;
 }
 .theme .note {
     --text-color: unset;
 }
<section>
    <p class="article">Article</p>
    <p class="note">Note</p>
</section>
<section class="theme">
    <p class="article">Article</p>
    <p class="note">Note</p>
</section>

Is it possible to make the second "Note" red again by unsetting the CSS variable?

I know that I could apply the CSS variable only to .article but assume I have a lot of similar elements where I want the theme applied but only a few exemptions. Then maintaining the selector would be rather tedious.

I could change the theme selector to .theme :not(.note) but that does not work on any .note elements nested in other elements.


Solution

  • You can use the value initial, since IE doesn't support CSS vars it is not an issue using initial here (also IE doesn't support it)

    .article,
    .note {
      color: var(--text-color, red);
    }
    
    .theme {
      --text-color: blue;
    }
    
    .theme .note {
      --text-color: initial;
    }
    <section>
      <p class="article">Article</p>
      <p class="note">Note</p>
    </section>
    <section class="theme">
      <p class="article">Article</p>
      <p class="note">Note</p>
    </section>