css实现table表头和列固定功能 | 您所在的位置:网站首页 › 如何让表格滚动时显示首行 › css实现table表头和列固定功能 |
背景
项目需要用表格展示数据,要求表头和左边两列能够在滚动的时候固定,考虑到目前开源的table组件库冗余了太多项目不需要的功能,其次也是为了防止数据过多的时候渲染太慢,于是决定用html和css实现。 功能 表头固定 左边两类固定 高度要自适应(table默认支持) 思路使用table的table-layout: fixed属性设置固定列宽,这样才能在左右滚动时计算出偏移量。结合css的position:sticky属性,设置第一行和左右两列粘性定位,其中第二列的偏移量根据第一列的宽度决定,以此类推,如果有三列固定,需要知道前两列的宽度。 table-layout: fixed根据MDN的描述,table-layout用于定义了用于布局表格单元格,行和列的算法,fixed属性值用于表示某一列的宽度仅由该列首行的单元格决定。因此,该单元格所在行之后的行并不会影响整个列宽。 代码实现 Title .table{ overflow:auto; width:400px; height:300px; /* 固定高度 */ border:1px solid #999; border-bottom: 0; border-right: 0; } table { border-collapse:separate; table-layout: fixed; width: 100%; /* 固定寬度 */ } td, th { border-right :1px solid #999; border-bottom :1px solid #999; box-sizing: border-box; /* 单元格宽高 */ width:100px; height:30px; } th { background-color:lightblue; } /* 控制左边固定的核心代码 */ td:nth-child(1), th:nth-child(1) { position:sticky; left:0; /* 首行在左 */ z-index:1; background-color:lightpink; } td:nth-child(2), th:nth-child(2) { position:sticky; left:100px; z-index:1; background-color:lightpink; } /* 控制表头固定的核心代码 */ thead tr th { position:sticky; top:0; /* 第一列最上 */ } th:nth-child(1), th:nth-child(2){ z-index:2; background-color:lightblue; } 表头1 表头2 表头3 表头4 表头5 我的高度不固定我的高度不固定我的高度不固定我的高度不固定我的高度不固定我的高度不固定 效果图 |
CopyRight 2018-2019 实验室设备网 版权所有 |