html - CSS - 使用 calc() 来保持元素的宽度相同

标签 html css calc

在 CSS 中可以实现这样的功能吗?

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

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

因此 div 始终与 elementOne 的宽度相同。

CSS 中是否有这样的功能,使用 calc() 或其他方式?

最佳答案

使用 CSS 变量:

<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>

您还可以在 calc() 函数中使用变量:

<div style="width: calc(var(--width) * 3); border: 1px solid;">Element four</div>

关于html - CSS - 使用 calc() 来保持元素的宽度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23076550/

相关文章:

javascript - 动态调整 DIV 高度以适应另一个 DIV 的内容?

php - Mysqli php 编辑表单

jquery - 如何将文本区域滚动条设置为右侧而不改变它的方向

css - React Carousal 渲染黑色背景的透明图像

css - 使用 calc 和 vw 在 2 个字体大小之间进行线性缩放

html - 为什么在 HTML 中使用 "for"关键字来绑定(bind)标签?

html - 背景覆盖背景大小

javascript - 使用现代 CSS 过渡使文本立即出现但逐渐淡出

css - calc() 返回百分比,而不是像素?