Fixed Table Header
For those rare occasions when you need to display a lot of tabular data in a table and want the table header to remain fixed and visible. NOTE: This won't work on Safari iOS which refuses to display the scrollbar.
Table heading | Table heading | Table heading |
---|
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
some content goes here | some content goes here | some content goes here |
Unfortunately, there is no way to apply CSS position:fixed to table headings. So my workaround is to use 2 tables -- one for the <thead> and a 2nd one for the <tbody>.
For this example, I used Bootstrap's built-in table classes.
<div class="table-responsive">
<table class="table" >
<thead>
<tr>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
</tr>
</thead>
</table>
<div id="scrolling"
<table class="table table-bordered table-striped">
<tbody>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
<tr>
<td>some content goes here</td>
<td>some content goes here</td>
<td>some content goes here</td>
</tr>
</tbody>
</table>
<!--end scrolling --></div>
<!--end table-responsive --></div>
To throw a vertical scrolbar on laptops/desktops, I wrapped the 2nd table inside a div tag with overflow: scroll and an expressed height in pixels. The div height is considerably shorter than the table.
table {
background:#008488;
color:#FFF;
margin-bottom:0;
}
.table-striped {background:#f2d9d9;}
/**For Laptops, Desktops only**/
@media only screen and (min-width: 1024px) {
#scrolling {
height: 150px; /**adjust as required**/
overflow-y:scroll;}
}
That's all there is to it. Hope you enjoyed this brief tutorial.