html表格,固定表头不动
时间: 2024-01-08 20:46:26 浏览: 245
在HTML表格中,要固定表头不动,可以使用CSS中的position属性和z-index属性。
首先,在表格之前添加一个div,设置其样式为position:fixed,top:0,left:0,z-index:1,height:表头的高度,width:表格的宽度。这样就可以将表头固定在页面顶部。
然后,在表格中每个单元格的样式中,设置其position:relative和z-index:2。这样可以让表格内容在表头下方显示。
最后,可以使用CSS的overflow属性来设置表格的滚动条,让表格内容可以滚动而不影响表头的固定。
以下是一个示例代码:
```html
<style>
#table-container {
position: fixed;
top: 0;
left: 0;
z-index: 1;
height: 50px;
width: 100%;
background-color: #fff;
border-bottom: 1px solid #ccc;
overflow-y: auto;
}
#table-container table {
width: 100%;
border-collapse: collapse;
}
#table-container td, #table-container th {
position: relative;
z-index: 2;
border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
#table-container th {
background-color: #f2f2f2;
}
#table-container tbody {
overflow-y: auto;
height: 200px;
}
</style>
<div id="table-container">
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
</tr>
<!-- more rows -->
</tbody>
</table>
</div>
```
在上面的代码中,表格的容器div的id为table-container,设置了固定定位、顶部为0、左侧为0、z-index为1、高度为50px、宽度为100%、背景色为白色、底部边框为1px实线、垂直方向上的滚动条为自动。表格的样式设置了宽度为100%、边框合并为collapse、单元格的相对定位、z-index为2、边框为1px实线、内边距为10px、水平居中对齐。表头的样式设置了背景色为浅灰色。表格主体的样式设置了垂直方向上的滚动条为自动、高度为200px。
阅读全文
相关推荐














