How to make the header table sticky in CSS.
To make the table header sticky/fixed, you need to target the header cells and use the 'sticky' position value along with a background color:
th { /* header cell */
position: sticky;
top: 0;
background-color: #F9F8F8;
}
If the table header has a border, you should apply it to the header cells and set the table border-collapse value equal to 'separate':
table {
border-collapse: separate;
border-spacing: 0;
}
th {
position: sticky;
top: 0;
background-color: #F9F8F8;
border-bottom: 2px solid #EB9486;
}
Here's a live demo of a table with a sticky header.
🧐 Need inspiration for your upcoming table components? Explore our gallery of tables or browse the entire component library for more design ideas.
Multiple sticky-headers table
You can create a table with multiple sticky headers by displaying multiple tables in a stack, each one with a sticky header. Here's a live demo of a table with multiple sticky headers.
In the HTML, you can create multiple <table>
elements and make each of the <thead>
elements sticky:
<table class="table" aria-label="Table Example">
<thead class="table__header table__header--sticky">
<tr class="table__row">
<th class="table__cell" scope="col">Heading Label 1</th>
<!-- ... other th elements -->
</tr>
</thead>
<tbody>
<!-- table body content here -->
</tbody>
</table>
<table class="table" aria-label="Table Example">
<thead class="table__header table__header--sticky">
<!-- table header content here -->
</thead>
<tbody>
<!-- table body content here -->
</tbody>
</table>
<!-- other table elements here -->
.table {
position: relative;
z-index: 1;
}
.table__cell { /* header cell */
position: sticky;
top: 0;
background-color: hsl(0, 0%, 100%);
}