Mar*_* M. 13 html css calc css3
是这样的可能在CSS?
<table>
<tr>
<td id="elementOne">elementOne</td>
<td id="elementtwo">elementtwo</td>
</tr>
</table>
<div style="width: calc(document.getElementById(elementOne).width)"></div>
Run Code Online (Sandbox Code Playgroud)
因此div总是与宽度相同elementOne.
CSS中是否有这样的功能,使用calc()或其他方法?
Sim*_*gét 12
使用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>
Run Code Online (Sandbox Code Playgroud)
您还可以在calc()函数中使用变量:
<div style="width: calc(var(--width) * 3); border: 1px solid;">Element four</div>
Run Code Online (Sandbox Code Playgroud)
leo*_*leo 11
不,这是不可能的CSS.
对于你将不得不使用JavaScript(document.getElementById(elementOne).offsetWidth或类似的,这取决于什么宽度你正在寻找).Calc是用来做数学,不执行脚本.没有办法将JS放在CSS语句中,就像你试图做的那样.
有关JS位更多的帮助,请参阅如何重新获取一个HTML元素的实际宽度和高度?
编辑:关于为什么这会是一个坏主意了一些背景材料在CSS中,实现自身价值计算CSS(TL; DR:它已审结爆炸的事情)