纯CSS实现Table固定表头和首列

Table固定表头和首列这种需求应该比较常见。以往的做法,需要写一大堆脚本,而现在,可以使用position:sticky轻松实现这个效果。

.table-container {
width: 100%;
height: 100%;
overflow: auto;
}

/* 首列固定 */
.table-container thead tr > th:first-child,
.table-container tbody tr > td:first-child {
position: sticky;
left: 0;
z-index: 1;
}

/* 表头固定 */
.table-container thead tr > th {
position: sticky;
top: 0;
z-index: 2;
}

/* 表头首列强制最顶层 */
.table-container thead tr > th:first-child {
z-index: 3;
}

HTML结构上,必须将 <table> 放在 <div class="table-container"> 子节点,且内部不要有其他 position 设置。

已有2条评论
  1. Blaze 2021-11-12 00:59

    但是在表格上面还有其他内容的时候纯css就比较难,头部的内容不能左右滚动,
    div – 宽带 屏幕100% 可以上下滚动,不能左右滚动

    表格 – 上下左右滚动, 首行吸顶,首列固定

    没找到不需要js的解决方案

    • 否子戈 2021-11-15 22:28

      肯定的,css的能力是描述性质,很难像编程一样灵活