Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 calc with variables

Tags:

html

css

firefox

I am calculating some widths and margins depending on the number of childs.

Is it possible in css3 to have a variable like:

.someClass {
   width: -moz-calc(nrOfChilds * 80px);
}

Some other classes I got are written as follows:

.anotherClass:nth-child(n) {
   margin-left: -moz-calc(n * 50px);
}

Is it possible to use some variables like n or nrOfChilds? At the moment I declare my second example several times and change the first manually? I know javascript is a solution to this. But is there a native css3 solution for this?

/Kind regards

Christian

like image 292
Christian Avatar asked Jan 12 '12 10:01

Christian


2 Answers

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>
like image 106
Rob W Avatar answered Oct 19 '22 07:10

Rob W


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

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

like image 32
Boris Zbarsky Avatar answered Oct 19 '22 06:10

Boris Zbarsky