div悬浮在固定位置_纯css实现固定表头和锁定列
### table
表格是⼀个⽹站很常⽤的元素,⽤以展⽰⼤量的数据。在处理表格时,通常会加⼊许多功能,如斑马线、选中⾼亮、固定表头、锁定列等等,本篇⽂章主要介绍如何单纯的使⽤css实现固定⾏或列的功能。
### ⼀般做法
⼤部分的⽹上介绍的实现⽅式,甚⾄部分ui框架如iview等都是通过三⾄四个表格组合,然后js处理同步滚动来实现,这样的好处是容易实现,pc端也不会出现什么问题。但是在⼿机端时,会有严重的不同步滚动现象,处理的不好时,甚⾄会出现错位等,体验⾮常不好。
### 本⽂做法
主要使⽤了⼆个css属性
* table-layout: fixed
* posotion: sticky
### table-layout
为了让表格呈现滚动效果,必须设定table-layout: fixed,并且给与表格宽度
```css
table {
table-layout: fixed;
width: 100%;
}
```
### position
固定表格的⾏列需要使⽤到`posotion: sticky`设定
sticky的表现类似于relative和fixed的合体,在超过⽬标区域时,他会固定于⽬标位置
**注意:** `posotion: sticky`应⽤于table时,只能作⽤于`
`和``,并且必须定义⽬标位置left / right / top / bottom来实现固定效果
```
thead tr th {
position:sticky;
top:0;
}
```
简单说明这两个属性后,我们⾸先建⽴⼀个带表格的html页⾯
```html
Title
```
css部分如下
```
div{
overflow:auto;
width:400px;
height:290px; /* 固定⾼度 */ border:1px solid gray;
border-bottom: 0;
border-right: 0;
}
td, th {
border-right :1px solid gray; border-bottom :1px solid gray; width:100px;
height:30px;
box-sizing: border-box;
}
th {
background-color:lightblue;
}
table {
border-collapse:separate;
table-layout: fixed;
width: 100%; /* 固定寬度 */
}
td:first-child, th:first-child { position:sticky;
left:0; /* ⾸⾏在左 */
z-index:1;
background-color:lightpink;
}
thead tr th {
position:sticky;css固定定位
top:0; /* 第⼀列最上 */
}
th:first-child{
z-index:2;
background-color:lightblue;
}
```
最后的效果如下:
### 注意
* z-index很重要,需要仔细设置,尤其是对于ios
* 如果是固定多列,每⼀列需要注意设置好left的值
* ⾃测时,⼿机端安卓与ios测试各测试了两台,均是可以的,但是测试的机型不全,需要⾃⾏多测试

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。