Sometimes, we want to create a table fixed header and scrollable body with CSS.
In this article, we’ll look at how to create a table fixed header and scrollable body with CSS.
How to create a table fixed header and scrollable body with CSS?
To create a table fixed header and scrollable body with CSS, we set the thead element’s position
to sticky
.
For instance, we write
<div class="tableFixHead">
<table>
<thead>
<tr>
<th>TH 1</th>
<th>TH 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
</tr>
<tr>
<td>D1</td>
<td>D2</td>
</tr>
<tr>
<td>E1</td>
<td>E2</td>
</tr>
</tbody>
</table>
</div>
to add a table.
Then we write
.tableFixHead {
overflow: auto;
height: 100px;
}
.tableFixHead thead th {
position: sticky;
top: 0;
z-index: 1;
}
to add position: sticky;
to the th elements in the thead element to make the table header stick to the top.
And we set top
to 0 to make it stay at the top.
Conclusion
To create a table fixed header and scrollable body with CSS, we set the thead element’s position
to sticky
.