我正在尝试获取具有固定宽度 td
和可变宽度 td
的表格。
我正在使用 CSS calc()
函数,但不知何故我似乎无法在表格中使用 %
。
这就是我目前所拥有的:
<table border="0" style="width:100%;border-collapse:collapse;">
<tr style="width:100%">
<td style="width:30px;">1</td> <!--Fixed width-->
<td style="width: calc( (100% - 230px) / 100 * 40);">Title</td> <!--Width should be 40% of the remaining space-->
<td style="width: calc( (100% - 230px) / 100 * 40);">Interpret</td> <!--Width should be 40% of the remaining space-->
<td style="width: calc( (100% - 230px) / 100 * 20);">Album</td> <!--Width should be 20% of the remaining space-->
<td style="width:80px;">Year</td><!--Fixed width-->
<td style="width:180px;">YouTube</td><!--Fixed width-->
</tr>
</table>
在我看来,它应该可以工作,但事实并非如此。
有人知道怎么解决吗?或者对我如何实现目标有其他建议?
最佳答案
表格在分配列空间方面有困难的规则,因为默认情况下它们根据单元格的内容分配空间。 Calc (atm) 无法使用它。
但是你可以做的是设置 table-layout
table
的属性强制子 td
元素获得您声明的确切宽度。为此,您还需要在 table 上设置一个宽度
(100%
有效)。
table{
table-layout:fixed; /* this keeps your columns with at the defined width */
width: 100%; /* a width must be specified */
display: table; /* required for table-layout to be used
(since this is the default value it is normally not necessary;
just included for completeness) */
}
然后在其余列上使用纯百分比。
td.title, td.interpret{
width:40%;
}
td.album{
width:20%;
}
用完固定宽度列的空间后,剩余空间分配给相对宽度的列。
为此,您需要默认显示类型 display: table
(相对于 display: block
)。然而,这意味着您不能再为表格设置高度
(包括min-height
和max-height
)。
关于css - 对表格使用 calc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19259569/