Search code examples
csscss-variablescss-calc

Can a CSS variable be used in the recalculation of its own value?


In CSS, can we we multiply a variable by some integer like the code below ?

:root {
     --x: 1em;
}

.class2 {
     --x: calc(2em * var(--x));
}

Solution

  • A quick check on the MDN docs unfortunately did not shine light on this. So unless you're willing to dive into the spec, here's a quick test:

    :root {
      --x: 4em;
    }
    
    .class2 {
      --x: calc(0.5 * var(--x));
      font-size: var(--x);
    }
    <div class="class2">
      Test - doesn't work as intended
    </div>

    By the looks of it not only does the calculcation not work - which is unfortunate by itself - but it even seems to invalidate the custom property for .class2.

    Just to make sure the formula/approach of using other variables to create computed variables in general is valid:

    :root {
      --x: 4em;
    }
    
    .class2 {
      --y: calc(0.5 * var(--x));
      font-size: var(--y);
    }
    <div class="class2">
      Test - <strike>doesn't</strike> works as intended
    </div>