根据 CSS 规范,当表格具有 table-layout:fixed
时属性,其宽度计算如下:
...the width of each column is determined as follows:
- A column element with a value other than 'auto' for the 'width' property sets the width for that column.
Otherwise, a cell in the first row with a value other than 'auto' for the 'width' property determines the width for that column. If the cell spans more than one column, the width is divided over the columns.
Any remaining columns equally divide the remaining horizontal table space (minus borders or cell spacing).
The width of the table is then the greater of the value of the 'width' property for the table element and the sum of the column widths (plus cell spacing or borders).
我对此的理解是:
- 计算每列的宽度(使用
width
元素的<col>
属性(如果存在,则优先) - 列宽总计
- 如果列宽总计大于
width
<table>
的属性(property)元素,那么表格将与列宽总和一样宽。
但是,在下面的示例中,我有一个表格,其中一行包含三个单元格。使用 <col>
将每列的宽度设置为 100 像素元素。表格元素没有分配宽度,它是 <div>
的子元素。宽度为 200 像素。
我预计表格的宽度为 300 像素,因此它会溢出其父项 <div>
。然而,相反,该表只有 200 像素宽(即与其父 <div>
一样宽),因此每列都缩小到 66.6 像素宽。 (我已经检查了最新的 Safari、Chrome、Firefox 和 Edge。)
为什么表格的宽度只有 200 像素,而不是 300 像素?
<div style="background:black; color:white; width:300px;">300px</div>
<br>
<div style="background:black; color:white; width:200px;">200px</div>
<br>
<div style="width:200px; background:green; overflow:scroll;">
<table style="table-layout:fixed; border-collapse:collapse;">
<col style="width:100px;">
<col style="width:100px;">
<col style="width:100px;">
<tr>
<td>1</td>
<td>2</td>
<td style="background:red;">3</td>
</tr>
</table>
</div>
(我给 <div>
一个绿色背景,给 overflow:hidden
和第三个单元格一个红色背景,以使意想不到的结果更清晰。)
最佳答案
您对规则的解释是正确的。问题是表格的宽度没有设置,所以浏览器无法与列宽总和进行比较。只需设置表格的宽度,甚至 width: 0px
也可以。
<div style="background:black; color:white; width:300px;">300px</div>
<br>
<div style="background:black; color:white; width:200px;">200px</div>
<br>
<div style="width:200px; background:green; overflow:scroll;">
<table style="table-layout:fixed; border-collapse:collapse;width:0px">
<col style="width:100px;">
<col style="width:100px;">
<col style="width:100px;">
<tr>
<td>1</td>
<td>2</td>
<td style="background:red;">3</td>
</tr>
</table>
</div>
关于html - 为什么我的固定布局表格不如其列宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40818989/