固定表格布局

Avatar of Chris Coyier
Chris Coyier 发表

DigitalOcean 提供适用于旅程各个阶段的云产品。立即开始使用 价值$200 的免费积分!

表格有一个 CSS 属性,在我看来,它支持良好、鲜为人知,而且非常有用。它改变了表格的渲染方式,从而提供更稳固、更可预测的布局。

它就是

table {
  table-layout: fixed;
}

table-layout 的默认属性是 auto,我认为大多数人都熟悉这种表格布局。这种风格在我看来感觉很松散,很奇怪。以下是一些探索

查看 CodePen 上 Chris Coyier (@chriscoyier) 编写的 默认表格很奇怪。.

使用 table-layout: fixed;

有了这个属性/值,事情变得更加稳固和可预测。

布局根据第一行固定。设置它们的宽度,表格的其余部分将随之而来。

这有点复杂,但并不多。以下是一些探索

查看 CodePen 上 Chris Coyier (@chriscoyier) 编写的 固定表格解决了一些问题.

用例

我之所以研究它,是因为我试图为 CodePen 上列表视图中的 Pens 保持统一的行高(即不换行 Pens 标题),但又不想让表格的宽度过大。这效果很好。

我想你们大多数人知道这一点:**表格用于表格数据和电子邮件。**而不是网页布局,因为原因.

实际的 HTML 和 CSS

我想大多数用例都像这样

<table class="users">
  <thead>
    <tr>
      <th class="row-1 row-ID">ID</th>
      <th class="row-2 row-name">Name</th>
      <th class="row-3 row-job">Job</th>
      <th class="row-4 row-email">Email<th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0001</td>
      <td>Johnny Five</td>
      <td>Robotin'</td>
      <td>[email protected]</td>
    </tr>
    <tr>
      <td>0002</td>
      <td>Super Superlonglastnamesmith</td>
      <td>Doin' stuff</td>
      <td>[email protected]</td>
    </tr>
  </tbody>
</table>
.users {
  table-layout: fixed;
  width: 100%;
  white-space: nowrap;
}
.users td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Column widths are based on these cells */
.row-ID {
  width: 10%;
}
.row-name {
  width: 40%;
}
.row-job {
  width: 30%;
}
.row-email {
  width: 20%;
}

查看 CodePen 上 Chris Coyier (@chriscoyier) 编写的 xFcrp.

为了确保万无一失,请知道可以使用 <col> 元素来设置列宽,因为这些元素会影响第一行的单元格,而第一行的单元格正是设置表格其余部分基础的关键。

布局速度

我听说这种表格布局方式也更快,这是有道理的,因为不需要分析整个表格的内容来确定列宽。不过,我还没有这方面的数据。

在电子邮件中

Campaign Montior 的 电子邮件客户端中 CSS 支持图表 显示 table-layout 在各处都受到支持。

更多信息

后续推文