CSS table-layout:用 fixed 控制表格列宽

要让后续行的内容不影响列宽,请同时指定 table-layout: fixed 和 width。默认的 auto 会把单元格内容纳入列宽计算。使用固定布局时,还要单独决定长内容是换行还是显示省略号。

为什么设定宽度后表格仍会变宽

自动布局中,无空格的长文本、大图片或 white-space: nowrap 会提高列的最小宽度,导致表格超过 width: 500px。固定布局优先使用 <col> 的宽度,其次使用首行单元格宽度,再把剩余空间分给未指定宽度的列。如果列、边框或间距需要更多空间,表格仍可能变宽。 CSS 2.2 · Automatic table layout CSS 2.2 · Fixed table layout

用相同数据比较 auto 和 fixed

将代码保存为 table-layout.html 并在浏览器中打开。两个表格使用同一个文件名和 width: 500px。第一个表格为把文件名放在一行内而变宽。第二个表格给首列指定 120px,把其余空间给第二列,并用省略号截断长值。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较表格和列的宽度</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    .jb-table-scroll { overflow-x: auto; margin-bottom: 24px; }
    table { width: 500px; border-collapse: collapse; }
    th, td { border: 1px solid #8a9bad; padding: 8px; text-align: left; }
    th { background: #edf3fa; }
    .filename { font-family: monospace; }
    .auto .filename { white-space: nowrap; }
    .fixed { table-layout: fixed; }
    .fixed th:first-child { width: 120px; }
    .fixed .filename {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  </style>
</head>
<body>
<h1>表格宽度与长值</h1>
<div class="jb-table-scroll" tabindex="0" role="region" aria-labelledby="auto-caption">
  <table class="jb-table-01 auto">
    <caption id="auto-caption">auto:随内容扩展</caption>
    <thead><tr><th scope="col">类型</th><th scope="col">文件名</th></tr></thead>
    <tbody><tr><td>文档</td><td class="filename">quarterly-report-for-the-international-development-team-with-regional-appendices-and-budget-tables-2024.pdf</td></tr></tbody>
  </table>
</div>
<div class="jb-table-scroll" tabindex="0" role="region" aria-labelledby="fixed-caption">
  <table class="jb-table-01 fixed">
    <caption id="fixed-caption">fixed:在 500px 内布局</caption>
    <thead><tr><th scope="col">类型</th><th scope="col">文件名</th></tr></thead>
    <tbody><tr><td>文档</td><td class="filename">quarterly-report-for-the-international-development-team-with-regional-appendices-and-budget-tables-2024.pdf</td></tr></tbody>
  </table>
</div>
</body>
</html>

在开发者工具中比较两个 table 的宽度。只关闭第二个表格的 text-overflow 时,省略号会消失,文字仍会被裁切。窗口较窄时,用 Tab 将焦点移到滚动区域,再用方向键横向移动。

让长单元格换行或显示省略号

要显示完整文件名,用下面的 CSS 替换第二个表格中文件名单元格的规则。white-space: normal 允许换行,overflow-wrap: anywhere 让没有空格的长值也能折行。列宽保持不变,行高可能增加。

.fixed .filename {
  white-space: normal;
  overflow-wrap: anywhere;
}

省略号由 white-space: nowrap、overflow: hidden 和 text-overflow: ellipsis 共同实现。读者还需要完整值时,请提供展开或详情视图等访问方式。 CSS Overflow · text-overflow

调整列宽和表格总宽

把首列从 120px 改成 160px,第二列在同一个 500px 表格中就会变窄。比较后恢复 120px。需要指定多列宽度时,可在 <colgroup> 中使用 <col>。

如果表格要随容器缩放,可用 width: 100%。在很窄的容器里,120px 的首列可能让第二列剩余空间太小。可以为首列改用百分比,或者在数字和日期需要单行显示时保留最小宽度和横向滚动。