html - 为什么我的固定布局表格不如其列宽?

标签 html css html-table

根据 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 像素元素。表格元素没有分配宽度,它是 <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/

相关文章:

javascript - HTML5 Canvas - 绘制重叠的多边形

javascript - 如何实现 Facebook 的 `Drag Links/Photos Here` ?

javascript - 我怎样才能控制鼠标滚动事件,然后在 html、body 上做一个动画?

html - mat-card 中的内容未使用 flex 居中

html - 用数据做同心正方形

html - 隐藏所有行并显示所选

javascript - 使用 jquery 根据背景颜色对表格行进行排序

html - 使用宽度和高度属性缩放图像以适合指定的矩形

css - 为什么不透明度没有动画?

javascript - 数据表按钮和搜索框位置