You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置带表头表格:除一列外适配内容,末列占剩余空间

表格列宽自适应与剩余空间填充方案

需求:表格中除一列外,其余所有列宽度完全适配内容,屏幕缩放时宽度保持不变;指定列填充剩余空间,宽度随窗口大小调整。此前通过硬编码列宽实现效果,但无法根据内容自动调整列宽。

现有代码:

CSS

table {
  display: table;
  width: 100%;
  table-layout: fixed;
  position: absolute;
  top: 0;
}

.small {
  background: green;
  width: 80px;
}

.extend {
  background: red;
}

HTML

<table>
  <thead>
    <th class="small">Column 1</th>
    <th class="extend">Column 2</th>
    <th class="small">Column 3</th>
  </thead>
  <tbody>
    <tr>
      <td class="small">First column</td>
      <td class="extend">This column should fill the remaining space </td>
      <td class="small">Small column 2</td>
    </tr>
  </tbody>
</table>

解决方案

修改CSS,调整表格布局模式并移除硬编码列宽:

table {
  display: table;
  width: 100%;
  position: absolute;
  top: 0;
}

.small {
  background: green;
}

.extend {
  background: red;
  width: 100%;
}

对应的HTML无需修改:

<table>
  <thead>
    <th class="small">Column 1</th>
    <th class="extend">Column 2</th>
    <th class="small">Column 3</th>
  </thead>
  <tbody>
    <tr>
      <td class="small">First column</td>
      <td class="extend">This column should fill the remaining space </td>
      <td class="small">Small column 2</td>
    </tr>
  </tbody>
</table>

原理说明:

  • 移除table-layout: fixed后,表格使用默认的auto布局模式,会自动根据列内内容计算最小必要宽度。
  • 给需要填充剩余空间的列设置width: 100%,浏览器会优先让其他列适配内容,再将剩余的全部空间分配给该列,窗口缩放时该列宽度随之调整,其他列保持内容宽度不变。

内容的提问来源于stack exchange,提问作者kat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:40:08