如何使用 CSS 固定 Web 页面表头
要在 web 页面上设置表头固定,可以使用 CSS 的 position 属性来实现。以下是一个示例:
HTML 代码:
<div class='table-container'>
<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>
<!-- 其他行数据 -->
</tbody>
</table>
</div>
CSS 代码:
.table-container {
overflow-y: scroll;
height: 300px; /* 需要设置一个固定的高度,以限制表格的显示区域 */
}
table {
width: 100%;
table-layout: fixed;
}
thead th {
position: sticky;
top: 0;
background-color: #fff; /* 设置表头的背景色 */
z-index: 999; /* 设置一个较高的 z-index 值,确保表头在顶部显示 */
}
在上述示例中,通过设置 .table-container 的 overflow-y: scroll; 和 height: 300px;,创建了一个固定高度的表格容器。然后,使用 position: sticky;、top: 0; 和 background-color 属性将 thead 元素的表头固定在顶部。最后,通过 z-index 属性确保表头在顶部显示。
请注意,为了实现表头固定,表格容器的高度必须是固定的,否则表格会自动调整大小以适应内容,导致表头无法固定。
原文地址: https://www.cveoy.top/t/topic/qmUJ 著作权归作者所有。请勿转载和采集!