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

HTML table如何实现首尾列固定、中间列可横向滚动效果?

实现可行性说明

可以实现,不需要依赖jQuery DataTables这类第三方组件,仅用原生HTML + 基础CSS即可完成,不需要写任何JS逻辑。注意纯HTML(无CSS样式控制)无法实现该效果,因为固定定位、滚动控制都需要CSS完成。

核心实现思路
  • 给表格套一层外层容器,设置容器overflow-x: auto,让容器宽度小于表格总宽度时出现横向滚动条
  • 首列、尾列分别设置position: sticky,首列加left: 0固定在容器左边缘,尾列加right: 0固定在容器右边缘
  • 给固定列设置不透明背景色,避免滚动时中间列内容和固定列重叠
  • 给固定列设置稍高的z-index,保证固定列层级高于中间可滚动列
完整示例代码

HTML 结构

<div class="table-scroll-wrapper">
  <table class="fixed-side-table">
    <thead>
      <tr>
        <th>固定首列</th>
        <th>中间列1</th>
        <th>中间列2</th>
        <th>中间列3</th>
        <th>中间列4</th>
        <th>中间列5</th>
        <th>固定尾列</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>行1首列</td>
        <td>行1列2</td>
        <td>行1列3</td>
        <td>行1列4</td>
        <td>行1列5</td>
        <td>行1列6</td>
        <td>行1尾列</td>
      </tr>
      <tr>
        <td>行2首列</td>
        <td>行2列2</td>
        <td>行2列3</td>
        <td>行2列4</td>
        <td>行2列5</td>
        <td>行2列6</td>
        <td>行2尾列</td>
      </tr>
    </tbody>
  </table>
</div>

CSS 样式

/* 滚动容器 */
.table-scroll-wrapper {
  width: 100%;
  overflow-x: auto;
  /* 限制容器最大宽度,撑出滚动条 */
  max-width: 800px;
}

/* 表格基础样式 */
.fixed-side-table {
  width: 1200px; /* 表格总宽度大于容器宽度,触发滚动 */
  border-collapse: collapse;
}
.fixed-side-table th, .fixed-side-table td {
  border: 1px solid #eee;
  padding: 8px 12px;
}

/* 固定首列 */
.fixed-side-table th:first-child,
.fixed-side-table td:first-child {
  position: sticky;
  left: 0;
  background: #fff;
  z-index: 2;
}

/* 固定尾列 */
.fixed-side-table th:last-child,
.fixed-side-table td:last-child {
  position: sticky;
  right: 0;
  background: #fff;
  z-index: 2;
}

/* 可选:表头固定在顶部 */
.fixed-side-table th {
  position: sticky;
  top: 0;
  z-index: 3;
}
/* 首列表头层级最高,避免横向滚动时和其他表头重叠 */
.fixed-side-table th:first-child {
  z-index: 4;
}
注意事项
  • position: sticky 兼容所有现代浏览器(Chrome、Firefox、Safari、Edge),仅IE全版本不支持,有IE兼容需求才需要考虑第三方组件方案
  • 固定列必须设置不透明背景,否则滚动时中间内容会透上来
  • 如果需要同时固定表头,给th加top: 0的sticky定位即可,注意调整z-index避免层级冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 02:45:03