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

CSS实现响应式表格时表格数据与表头无法对齐问题求助

问题根源

你当前的代码核心问题是修改了表格元素的默认渲染规则,但没有同步处理表头和表体的布局逻辑:

  1. 给.panel__table设置了display: block,原生表格的自动列宽计算逻辑失效
  2. 仅给tbody设置了display: table和100%宽度,thead仍沿用块级元素的默认流式布局,和tbody的列宽计算逻辑完全独立,自然无法对齐。

修复方案

直接替换你的CSS代码为以下内容即可:

.panel {
    margin: 20px auto;
}

.panel__title {
    width: 100%;
    background-color: var(--primary-color);
    color: #fff;
    padding: 10px 0 10px 25px;
    border-radius: 25px 25px 0 0;
    box-sizing: border-box;
}

.panel__table {
    display: block;
    overflow-x: auto;
    border-spacing: 0;
    border: 3px solid var(--primary-color);
    border-radius: 0 0 25px 25px;
    padding: 13px;
    box-sizing: border-box;
}

/* 统一表头、表体的布局规则,核心修复逻辑 */
.panel__table thead,
.panel__table tbody {
    display: table;
    width: 100%;
    table-layout: fixed;
}

.panel__table th,
.panel__table td {
    text-align: left;
    padding: 16px;
    word-wrap: break-word;
}

.panel__table td {
    font-weight: 400;
    font-size: 16px;
    line-height: 24px;
}

.panel__table tr:nth-child(even) {
    background-color: #f5f5f5;
}

可选优化

如果需要自定义各列宽度占比,避免内容挤压,可以额外添加列宽规则:

/* 示例:自定义各列宽度占比,可按需调整 */
.panel__table th:nth-child(1) { width: 8%; }  /* Hop列 */
.panel__table th:nth-child(2) { width: 32%; } /* From列 */
.panel__table th:nth-child(3) { width: 22%; } /* By列 */
.panel__table th:nth-child(4) { width: 10%; } /* With列 */
.panel__table th:nth-child(5) { width: 28%; } /* Time列 */

内容的提问来源于stack exchange,提问作者saibot-tsch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:45:00