I am trying to have multiple rows under the <thead>
tag be stickied while the rest of the table is scrollable.
This answer on SO shows how to sticky the header to the top using position: sticky
tag but doesn't show how to sticky multiple rows within <thead>
.
Using the CSS code mentioned in the link thead th { position: sticky; top: 0; }
will only sticky the first row within <thead>
.
Thanks for the help!
If both the top values are same then, it is going to overlap one on each other, change the second header's top
value with first header's height
. Shown below
thead tr:nth-child(1) th { position: sticky; top: 0; }
thead tr:nth-child(2) th { position: sticky; top: 43px; }
Here top: 43px
is a height of first header's
Full Example
Example link to jsfiddle
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#customers td,
#customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers tr:nth-child(even) {
background-color: #f2f2f2;
}
#customers tr:hover {
background-color: #ddd;
}
#customers th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
thead tr:nth-child(1) th {
position: sticky;
top: 0;
}
thead tr:nth-child(2) th {
position: sticky;
top: 43px;
}
<table id="customers">
<thead>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<th>Company 2</th>
<th>Contact 2</th>
<th>Country 2</th>
</tr>
</thead>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Christina Berglund</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Königlich Essen</td>
<td>Philip Cramer</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>North/South</td>
<td>Simon Crowther</td>
<td>UK</td>
</tr>
<tr>
<td>Paris spécialités</td>
<td>Marie Bertrand</td>
<td>France</td>
</tr>
<tr>
<td>Some repeated content</td>
<td>Some repeated content</td>
<td>Some repeated content</td>
</tr>
<tr>
<td>Some repeated content</td>
<td>Some repeated content</td>
<td>Some repeated content</td>
</tr>
<tr>
<td>Some repeated content</td>
<td>Some repeated content</td>
<td>Some repeated content</td>
</tr>
<tr>
<td>Some repeated content</td>
<td>Some repeated content</td>
<td>Some repeated content</td>
</tr>
</table>