gpt4 book ai didi

html - 为什么我的固定布局表没有它的列那么宽?

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:40 24 4
gpt4 key购买 nike

根据 CSS 规范,当表格具有 table-layout:fixed属性,它的宽度是这样计算的:

...the width of each column is determined as follows:

  1. A column element with a value other than 'auto' for the 'width' property sets the width for that column.
  2. 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.

  3. 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).

我的理解是:

  1. 计算每列的宽度(使用 width 元素的 <col> 属性,如果存在,则优先)
  2. 列宽合计
  3. 如果列宽总和大于width <table> 的属性(property)元素,则表格的宽度将与列宽总和一样宽。

但是 — 在下面的示例中,我有一个表格,其中一行包含三个单元格。使用 <col> 将每列的宽度设置为 100 像素元素。 table 元素没有分配给它的宽度,它是 <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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com