skip to Main Content

How do I recalculate a new value of a CSS variable (custom property) in a sub-element using calc() to modify the value inherited from a parent element?

This doesn’t work:

div {
  height: var(--foo);
  border: 1px solid #f00;
}

.a {
  --foo: 100px;
}

.b {
  --foo: calc(var(--foo) - 25px);
}
<div class=a>
  <div class=b>
    foo box
  </div>
</div>

The browser seems to completely unset the value of --foo on .b.

Using the inherit keyword in the calc() expression also doesn’t work.

2

Answers


  1. you can’t directly modify the value of a CSS variable that is inherited from a parent element. However, you can achieve this by using a different approach: setting a new CSS variable specifically for the sub-element and use that variable to calculate the desired value.

    div {
      height: var(--foo);
      border: 1px solid #f00;
    }
    
    .a {
      --foo: 100px;
    }
    
    .b {
      /* Set a new variable for the sub-element */
      --sub-foo: calc(var(--foo) - 25px);
      /* Use the new variable instead of modifying --foo */
      height: var(--sub-foo);
    }
    
    Login or Signup to reply.
  2. Declare the custom property (variable) and then declare the height with the classes

    div {
      --foo: 100px;
      border: 1px solid #f00;
    }
    
    .a {
      height: var(--foo);
    }
    
    .b {
      height: calc(var(--foo) - 25px);
    }
    <div class=a>
      <div class=b>
        foo box
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search