CSS - Use calc() to keep widths of elements the same

Marc M. picture Marc M. · Apr 15, 2014 · Viewed 70k times · Source

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?

Answer

Simon Rig&#233;t picture Simon Rigét · Jan 31, 2017

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>