Sometimes, we want to create an HTML table with a fixed or frozen left column and a scrollable body with CSS.
In this article, we’ll look at how to create an HTML table with a fixed or frozen left column and a scrollable body with CSS.
How to create an HTML table with a fixed or frozen left column and a scrollable body with CSS?
To create an HTML table with a fixed or frozen left column and a scrollable body with CSS, we use sticky position.
For example, we write
<div class="tscroll">
<table>
<thead>
<tr>
<th></th>
<th colspan="1">Heading 1</th>
<th colspan="1">Heading 2</th>
<th colspan="2">Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>9:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
<tr>
<td>10:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
<tr>
<td>11:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
<tr>
<td>13:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
<tr>
<td>14:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
\
</tr>
<tr>
<td>15:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
<tr>
<td>16:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
<tr>
<td>17:00</td>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
</tbody>
</table>
</div>
to add div with a table inside.
Then we write
.tscroll {
width: 400px;
overflow-x: scroll;
margin-bottom: 10px;
border: solid black 1px;
}
.tscroll table td:first-child {
position: sticky;
left: 0;
background-color: #ddd;
}
.tscroll td,
.tscroll th {
border-bottom: dashed #888 1px;
}
We make the first column’s cells sticky and add a background color to them with
.tscroll table td:first-child {
position: sticky;
left: 0;
background-color: #ddd;
}
Then we make the div scrollable horizontally with overflow-x: scroll;
.
Conclusion
To create an HTML table with a fixed or frozen left column and a scrollable body with CSS, we use sticky position.