Today we will learn about how to create a scrollable table in which we are keeping the header fixed using CSS. As we have seen, sometimes when we try to put a big table with a lot of rows on our page then it might happen that some of the table content cannot be visible because the table size is a bit larger and the user may have a bad experience in viewing the content due to which the user will need to scroll back to the top to know the heading of the columns. So, for this kind of purpose we require a scrolling table with fixed header in HTML with CSS.
Table of Contents
Code for Fixed Header Table with Scrolling Body in CSS
Demo
See the Pen Create scrollable table with fixed header in HTML with pure CSS by Arpit Mittal (@codingiseasy) on CodePen.
HTML
<div class="table-wrap">
<table>
<thead>
<tr>
<th>S No.</th>
<th>Company</th>
<th>Website</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>StartupHolic</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>2</td>
<td>AAWP</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>3</td>
<td>Affiliatable</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>4</td>
<td>TableLabs</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>5</td>
<td>WP Table Builder</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>6</td>
<td>Ultimate Blocks</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>7</td>
<td>AzonPress</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
<tr>
<td>8</td>
<td>AmaLinks Pro</td>
<td><a href="https://startupholic.com">Visit Now</a></td>
</tr>
</tbody>
</table>
</div>
CSS
.table-wrap {
max-height: 300px;
overflow-x: hidden;
overflow-y: auto;
}
table {
border-collapse: collapse;
width: 100%;
}
thead th {
position: sticky;
top: 0;
}
html {
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
position: relative;
}
body {
padding: 20px;
-webkit-font-smoothing: antialiased;
}
th, td {
border: 1px solid #ccc;
padding: 0.5rem;
font: caption;
outline-offset: -1px;
}
th {
font-weight: 700;
z-index: 1;
padding: 1rem 0.5rem;
}
th:after {
content: "";
display: block;
position: absolute;
background-color: #d4ebf2;
top: -1px;
left: 0;
right: 0;
bottom: 0;
z-index: -1;
outline: 1px solid #ccc;
}
.table-wrap {
border: 1px solid #ccc;
-webkit-overflow-scrolling: touch;
}
table {
margin: -1px;
width: calc(100% + 2px);
}
tr:nth-of-type(even) {
background-color: whitesmoke;
}
td:nth-of-type(3) {
white-space: nowrap;
}
.table-wrap::-webkit-scrollbar {
-webkit-appearance: none;
border-left: 1px solid #ccc;
background-image: linear-gradient(to top, whitesmoke, white);
}
.table-wrap::-webkit-scrollbar:vertical {
width: 0.6rem;
}
.table-wrap::-webkit-scrollbar:horizontal {
width: 0.6rem;
}
.table-wrap::-webkit-scrollbar-thumb {
border-radius: 0.8rem;
background-color: rgba(51, 51, 51, 0.5);
}