22

Is something like this possible in CSS?

<table>
  <tr>
    <td id="elementOne">elementOne</td>
    <td id="elementtwo">elementtwo</td>
  </tr>
</table>

<div style="width: calc(document.getElementById(elementOne).width)"></div>

So that the div is always the same width as elementOne.

Is there such a feature in CSS, using calc() or some other means?

Zach Saucier
  • 21,903
  • 12
  • 75
  • 126
Marc M.
  • 3,052
  • 3
  • 25
  • 51
  • No, there is not such feature (AFAIK something like that has been supported in IE **until** version 7) but you have an even more powerful feature: JavaScript. – Adriano Repetti Apr 15 '14 at 06:57
  • 1
    This was called `expression()` in IE, and it was a bad idea: http://stackoverflow.com/questions/527861/value-calculation-for-css#answer-528361 – leo Apr 15 '14 at 07:06

3 Answers3

17

Use CSS variables:

<style>
:root { --width: 100px; } /* Set the variable --width */

table td{
  width: var(--width);    /* use it to set the width of TD elements */
  border: 1px solid;
}
</style>

<table>
  <tr>
    <td class="tab">elementOne</td>
    <td class="tab">elementtwo</td>
  </tr>
</table>

<!-- reuse the variable to set the width of the DIV element -->
<div style="width: var(--width); border: 1px solid;">Element three</div>

You can also use variables in the calc() function:

<div style="width: calc(var(--width) * 3); border: 1px solid;">Element four</div>
Simon Rigét
  • 2,211
  • 3
  • 26
  • 28
  • 1
    Be warned, that CSS variables are not supported very well in IE and Edge (and many other smaller browsers); http://caniuse.com/#feat=css-variables – carefulnow1 Apr 10 '17 at 22:47
15

No, it's not possible with CSS.

For that you will have to use JavaScript (document.getElementById(elementOne).offsetWidth or similar, depending on exactly what width you are looking for). Calc is used to do math, not execute scripts. There is no way of putting JS in a CSS statement, like you are trying to do.

For more help on the JS bit, see How do I retrieve an HTML element's actual width and height?

Edit: For some background on why this would be a bad idea to implement in CSS, se Value calculation for CSS (TL;DR: It has been tried. Things exploded)

Community
  • 1
  • 1
leo
  • 6,927
  • 6
  • 41
  • 62
0

Yes. There are 2 possible ways of doing this with CSS (although not with calc):

1) If you know how many columns you have, then just use % (i.e. 50% for 2 cols)

2) If you don't know how many columns you have or you maybe can't use % for whatever use-case you might have, then you can use flexbox. Depending on your browser compatibility target, you can combine the "old" and "new" syntax to get some awesome results.

Manatax
  • 3,563
  • 4
  • 27
  • 39