Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

calc

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?

like image 299
Marc M. Avatar asked Apr 15 '14 06:04

Marc M.


People also ask

How does the CALC () function work on values in CSS?

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.

What is Calc method in CSS?

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.

What CSS property is used for setting the width of an element?

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.

Is CSS calc dynamic?

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.


2 Answers

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>
like image 141
Simon Rigét Avatar answered Oct 21 '22 00:10

Simon Rigét


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)

like image 20
leo Avatar answered Oct 20 '22 23:10

leo