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

如何实现指定列占剩余宽度、其余列随内容收缩的等列宽表格?

实现自适应列宽的表格布局方案

方案一:原生Table标签实现

利用table的天然列宽统一特性,搭配CSS即可满足需求,这是兼容性最好的方案:

<style>
.table-wrapper {
  width: 100%;
  overflow-x: auto; /* 小屏幕下允许横向滚动 */
}
.adaptive-table {
  width: 100%;
  border-collapse: collapse;
}
.adaptive-table th, .adaptive-table td {
  border: 1px solid #ddd;
  padding: 8px;
  white-space: nowrap; /* 禁止内容换行 */
}
/* 第1、3、4列收缩至内容最小宽度 */
.adaptive-table th:nth-child(1),
.adaptive-table td:nth-child(1),
.adaptive-table th:nth-child(3),
.adaptive-table td:nth-child(3),
.adaptive-table th:nth-child(4),
.adaptive-table td:nth-child(4) {
  width: 1%;
}
/* 第2列占用剩余全部空间 */
.adaptive-table th:nth-child(2),
.adaptive-table td:nth-child(2) {
  width: auto;
  text-align: left;
}
</style>

<div class="table-wrapper">
  <table class="adaptive-table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Comments</th>
        <th>Votes Count</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>245325</td>
        <td>Lorem ipsum</td>
        <td>5</td>
        <td>2</td>
      </tr>
      <tr>
        <td>32</td>
        <td>Even longer title</td>
        <td>0</td>
        <td>1</td>
      </tr>
    </tbody>
  </table>
</div>

核心逻辑:给需要收缩的列设置width: 1%,配合white-space: nowrap让列宽自动适配内容的最小宽度;第2列不设置固定宽度,会自动填充容器的剩余空间。table会自动保证所有行的对应列宽度一致。

方案二:CSS Grid实现(非table标签)

如果偏好使用div等非table标签,CSS Grid可以实现类似flex的伸缩效果,同时确保列宽全局统一:

<style>
.grid-table {
  display: grid;
  width: 100%;
  grid-template-columns: min-content 1fr min-content min-content;
  border-collapse: collapse;
}
.grid-table > div {
  border: 1px solid #ddd;
  padding: 8px;
  white-space: nowrap;
}
.grid-table .header {
  font-weight: bold;
  background-color: #f5f5f5;
}
</style>

<div class="grid-table">
  <div class="header">ID</div>
  <div class="header">Title</div>
  <div class="header">Comments</div>
  <div class="header">Votes Count</div>
  
  <div>245325</div>
  <div>Lorem ipsum</div>
  <div>5</div>
  <div>2</div>
  
  <div>32</div>
  <div>Even longer title</div>
  <div>0</div>
  <div>1</div>
</div>

核心逻辑:grid-template-columns中的min-content会让对应列收缩到内容的最小宽度,1fr表示占据容器的剩余所有空间。Grid布局天生会让每一行的对应列保持相同宽度,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:50:26