过去3天,我一直在尝试将表格的thead固定在可滚动的div中,但失败了。
我有一个具有以下格式的表:
<div class='div_container'>
<table id='table'>
<thead>
<tr>
<th>header 1</th>
<th>header 2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
<tr class='resultsRow'>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr class='resultsRow'>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr class='resultsRow'>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr class='resultsRow'>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
<tbody>
<tr class='resultsRow'>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr class='resultsRow'>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
</table>
</div>
我正在尝试将标头固定在div的顶部,但我唯一得到的(除非完全失败)是thead固定的,但它超出了div的边距。
有什么办法解决这个问题吗?
我尝试同时使用CSS和js,但还是没有运气。
到目前为止,我的CSS:
.div_container{
overflow: scroll;
display: block;
height: 600px;
margin-left: 10%;
margin-right: 10%;
}
#table tbody .resultsRow td {
text-align: center;
}
thead {
position: sticky;
/* display: block; */
}
答案 0 :(得分:0)
使用position: sticky;
尝试此纯CSS固定表标头解决方案
div {
display: inline-block;
height: 200px;
overflow: auto
}
table th {
position: -webkit-sticky;
position: sticky;
top: 0;
}
table {
border-collapse: collapse;
}
th {
background-color: #ddd;
color: #fff;
}
th,
td {
padding: 1em .5em;
}
table tr {
color: #212121;
}
<div>
<table>
<thead>
<tr class="header">
<th>header 1</th>
<th>header 2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
</table>
</div>