2

I am trying to inherit the global font-family in a variable. However this does not work.

:root {
  --special-font: sans-serif;
}

html {
  font-family: serif;
}

.highlight {
  font-family: var(--special-font);
}

.special {
  --special-font: inherit;
}


/* .special {
  --special-font: serif;
} */


/* .special .highlight {
  font-family: inherit;
} */
<html>

<body>
  <div>
    <p>
      Standard Font: Serif
    </p>
    <p class="highlight">
      Highlight Font: Sans Serif
    </p>
  </div>
  <div class="special">
    <p class="highlight">
      Special Highlight: should be Serif
    </p>
  </div>
</body>

</html>

Both the commented out rules would work. But I would prefer to not repeat myself. Is there something I am missing?

Jeanot Zubler
  • 979
  • 2
  • 18
  • When you set up a variable, you cannot assign it another value later. Create 2 variables like `--standard-font` and `--highlight-font` and just use font-family: variable. `:root { --special-font: sans-serif; --serif-font: serif; } html { font-family: var(--serif-font); } .highlight { font-family: var(--special-font); } .special .highlight { font-family: var(--serif-font); }`` – Alexandra Batrak Nov 25 '22 at 16:01
  • Sorry for bad code format – Alexandra Batrak Nov 25 '22 at 16:07
  • 1
    @AlexandraBatrak That would be a workaround. But it is not correct, that a variable can't be changed later. If I specify `serif` instead of `inherit` in the `.special` selector, it works as expected. – Jeanot Zubler Nov 25 '22 at 16:10
  • You're right :D It works with `.special { --special-font: initial; }` – Alexandra Batrak Nov 25 '22 at 16:13

1 Answers1

3

Figured out what is happening, thanks to a comment, this question and this answer. I am not actually setting the variable to contain the value inherit but rather tell the variable to inherit its value.

In order do make my font-family inherit the documentwide font, I can set the variable to initial.For a variable this is an empty string, thereby setting the font-family property of my paragraph to its default behaviour, which is inherit.

Jeanot Zubler
  • 979
  • 2
  • 18