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?
CSS calc() is a function used for simple calculations to determine CSS property values right in CSS. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.
calc() The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used anywhere a <length> , <frequency> , <angle> , <time> , <percentage> , <number> , or <integer> is allowed.
The width CSS property sets an element's width. By default, it sets the width of the content area, but if box-sizing is set to border-box , it sets the width of the border area.
Using CSS Calc() to Dynamically Define an Element's Size️ Without JavaScript. The modern web is a flexible experience with so many screen sizes and devices to support. This means fluid, responsive designs are a requirement. The CSS calc() make it much easier to build fluid, responsive layouts.
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>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With