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

如何实现宽度100%且列宽随内容自适应调整的CSS表格?

解决方案

调整思路

  • 原有代码中的table-layout: fixed会强制表格使用固定列宽规则,无法根据内容自适应分配宽度,直接删除该行即可(默认值table-layout: auto会自动根据单元格内容计算列宽)
  • 给需要自动收缩的第1、3、4列设置极小的宽度值+禁止内容换行,浏览器会自动将这些列压缩到刚好容纳内容的最小宽度,剩余空间会全部分配给未设置宽度限制的第2列
  • 补充white-space: nowrap配置,保证原有溢出省略号的逻辑正常生效

最终可直接使用的CSS代码

.content-table {
    border-collapse: collapse;
    width: 100%;
}

.content-table th,
.content-table td {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 第1、3、4列自动收缩配置 */
.content-table :is(th, td):nth-child(1),
.content-table :is(th, td):nth-child(3),
.content-table :is(th, td):nth-child(4) {
    width: 1px;
}

可选补充配置

如果第2列不需要溢出省略,希望内容过长时自动换行,可以额外添加以下代码:

.content-table :is(th, td):nth-child(2) {
    white-space: normal;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:06:02