HTML代码:
标题1
标题2
标题3
内容1
内容2
内容3
内容1
内容2
内容3
CSS代码:
table {
width: 100%;
border-collapse: collapse;
}
th {
background-color: #f2f2f2;
position: sticky;
top: 0;
z-index: 1;
}
th,
td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #ddd;
}
tbody tr:hover {
background-color: #f5f5f5;
}
在CSS中,通过position:sticky
属性来实现表格头部固定,top:0
表示头部固定在相对于视口的顶部位置,z-index:1
表示头部悬浮在表格主体之上。同时,我们在表格主体中添加一些样式,让表格看起来更加美观。注意:IE和Edge旧版浏览器不支持position:sticky属性。
这个示例中只有文本会随着滚动而移动,如果需要多种类型的元素一起移动,可以将这些元素包裹在一个div中,让这个div固定在表格头部即可。
上一篇:表格同时为nil和非nil
下一篇:表格头部固定,但边框不固定