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

可双向滚动表格隔行左固定且随表上下滚动的纯CSS实现方案

核心实现思路

  1. 新增独立滚动容器作为表格的父元素,作为sticky定位的上下文,替换原来的视口定位逻辑
  2. 将fixed定位改为sticky定位,设置left: 0实现横向滚动时贴左效果,同时保留跟随行上下滚动的特性
  3. 调整表格宽度属性,确保内容超出时可以触发双向滚动

修改后完整代码

HTML

<body>
  <div class="table-container">
    <table id="table">
    </table>
  </div>
</body>

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.table-container {
  width: 100vw;
  height: 100vh;
  overflow: auto;
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
table {
  min-width: 100%;
}
.stickyDiv{
  position: sticky;
  left: 0;
  width: 100px; /* 可根据需求调整固定列宽度 */
  height: 100%;
  line-height: 44px;
  background-color: aliceblue;
  z-index: 1; /* 避免被后续单元格内容覆盖 */
}

JS

const table = document.getElementById('table')
for (var i = 0; i <100; i++){
  var k = 0
  for (var j = 0; j <100; j++){
    if (k == 0){
      var tr = table.insertRow(-1);  
      var tabCell = tr.insertCell(-1);
      tabCell.colSpan = "100"
      tabCell.style.height = "44px"
      div = document.createElement("div")
      div.setAttribute("class","stickyDiv")
      div.innerHTML = "entity " + i
      tabCell.appendChild(div)
      k++
    }
    if(k != 0){
      if(k == 1){
        var tr = table.insertRow(-1); 
      }
      var tabCell = tr.insertCell(-1);
      tabCell.innerHTML = "Column" + j
      tabCell.style.minWidth = "120px" /* 给普通列设置最小宽度,确保可触发横向滚动 */
      k++
    }
  }
}

实现效果

  • 横向滚动时,所有entity标题行的内容会始终贴在容器左侧,不会滑出可视区域
  • 纵向滚动时,标题行会跟随所属的行组正常上下移动,不会固定在视口位置
  • 全程纯CSS+原生JS实现,无抖动问题,兼容所有现代浏览器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:15:01