Search code examples
htmlcsscss-variables

Why display property set to inherit with CSS variable doesn't work?


I set the display property for divs to in line-block. I then created four classes:

  • no-var, which sets display to inherit
  • var, which sets display to a variable set to inherit
  • var-none, which sets display to a variable set to none
  • var-default, which sets display to a variable set to inherit and a default of grid

The actual style that is used by each class doesn't seem to be correct, though:

  • The no-var class correctly inherits display to block
  • The var class doesn't get the inherit value from the variable and displays as inline-block
  • The var-none class correctly sets display to none and is hidden
  • The var-default class doesn't get the inherit value from the variable and sets display to the default

For each of these classes I added variables and defaults for the color property, which all work as expected. Are variables supposed to ignore inherit and unset values?

:root {
  --display: inherit;
  --display-none: none;
  --color: red;
}
div  {
  display: inline-block;
  color: green;
}
.no-var {
  display: inherit;
  color: red;
}
.var {
  display: var(--display);
  color: var(--color);
}
.var-none {
  display: var(--display-none);
}
.var-default {
  display: var(--display, grid);
  color: var(--color, purple);
}
<div class="no-var">
  No variable
</div>
<div class="no-var">
  No variable
</div>
<div class="var">
  Variable
</div>
<div class="var">
  Variable
</div>
<div class="var-none">
  None
</div>
<div class="var-none">
  None
</div>
<div class="var-default">
  Default
</div>
<div class="var-default">
  Default
</div>


Solution

  • In such situation, inherit is used as a value for the custom property and will not be evaluted to the inherit value using var().

    Here is a basic example to understand the issue:

    .box {
      --c:inherit;
      color:var(--c,red);
    }
    <div>
      <div class="box">I am a text</div>
    </div>
    <div style="--c:blue">
      <div class="box">I am a text</div>
    </div>

    Note how in the second case we have a blue color because the custom property inherited this value from the top div then it's getting evaluted to that value. In the first case, we will use the default color because there is nothing to inherit.

    enter image description here

    In other words, inherit will be considered for the custom property and not for the property where you will evalute the custom property using var(). You will not find a custom property with a computed value equal to inherit BUT with a computed value equal to the inherited value.


    From the specification:

    Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules