可以使用 CSS 中的 position
和 z-index
属性来实现表格头部和脚部的固定样式。
首先,将表格头部和脚部分别放在一个 thead
和 tfoot
标签中,并设置它们的样式:
thead {
position: fixed;
top: 0;
background-color: #fff;
z-index: 999;
}
tfoot {
position: fixed;
bottom: 0;
background-color: #fff;
z-index: 999;
}
其中,position: fixed
属性将 thead
和 tfoot
固定在页面上,top: 0
和 bottom: 0
分别将它们固定在页面的顶部和底部,background-color
属性设置背景颜色,z-index
属性设置层次。
接下来,需要将表格内容向下移动,避免被 thead
遮挡。可以使用如下 CSS 代码:
tbody {
display: block;
margin-top: 80px; /* 与 thead 的高度相同 */
margin-bottom: 80px; /* 与 tfoot 的高度相同 */
}
其中,display: block
将 tbody
转换为块级元素,使得 margin-top
和 margin-bottom
可以生效。这两个属性的值需要与 thead
和 tfoot
的高度相同,以便保证表格内容被正确地显示出来。
完整的实现代码如下:
thead {
position: fixed;
top: 0;
background-color: #fff;
z-index: 999;
}
tfoot {
position: fixed;
bottom: 0;
background-color: #fff;
z-index: 999;
}
tbody {
display: block;
margin-top: 80px;
margin-bottom: 80px;
}
需要注意的是,这种方法只适用于固定列数的表格,如果表格列数不固定,可能需要使用 JavaScript 实现。