CSS3 calc with variables

Nowadays all major browsers support calculated CSS values with custom variables, via:

  • calc(...)
    • Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/calc
    • Browser support: https://caniuse.com/css-variables
  • var(--...)
    • Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/var
    • Browser support: https://caniuse.com/calc

Example

.somebar {
    /* I define the initial value of "--mydepth" */
    --mydepth: 1;
    width: calc(var(--mydepth) * 50px);
    
    height: 50px;
    background: green;
}

.level1 {
    --mydepth: 2;
}
.level2 {
    --mydepth: 3;
}
<h3>Example of: calc(var(--mydepth) * 50px)</h3>
<div class="somebar"></div>
<div class="somebar level1"></div>
<div class="somebar level2"></div>

<h3>Expected result (if supported by browser)</h3>
<div class="somebar" style="width:50px"></div>
<div class="somebar" style="width:100px"></div>
<div class="somebar" style="width:150px"></div>


(As of 2012) There's no way to do this in CSS3.

As of 2019 (and earlier) see the accepted answer above.


Have a look at LESS or .less if using .NET server side.

Tags:

Html

Css

Firefox