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

早过忘川 提交于 2019-12-04 00:44:33
leo

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)

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>

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!