如何固定 table 表头
时间: 2023-11-16 07:06:28 浏览: 36
可以使用 CSS 属性 `position: fixed` 和 `top` 来固定 table 表头。
具体实现步骤如下:
1. 在 table 的 thead 中添加一个新的 tr,用于存放表头的内容。
2. 将这个新的 tr 设为固定定位,并设置 top 属性为 0。
3. 为了让表头不遮挡表格内容,需要为表格添加一个新的 tbody 元素,并设置其样式为 `display: block; overflow: auto;`。
4. 在 CSS 中设置表头所在的 tr 的样式为 `position: fixed; top: 0;`。
以下是一个示例代码:
HTML:
```html
<table>
<thead>
<tr>
<th>表头1</th>
<th>表头2</th>
<th>表头3</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容1</td>
<td>内容2</td>
<td>内容3</td>
</tr>
<tr>
<td>内容4</td>
<td>内容5</td>
<td>内容6</td>
</tr>
<!-- more rows... -->
</tbody>
</table>
```
CSS:
```css
table {
border-collapse: collapse;
width: 100%;
}
thead tr {
position: fixed;
top: 0;
background-color: #fff;
}
tbody {
display: block;
overflow: auto;
height: 300px; /* 设置表格容器的高度 */
}
tbody tr:nth-child(even) {
background-color: #f2f2f2;
}
```
注意:固定表头时需注意表格容器的高度,如果表格内容过多,容器高度不足以容纳所有内容,则表头和内容会出现错位的情况。