HTML table headers always visible at top of window when viewing a large table
Check out jQuery.floatThead (demos available) which is very cool, can work with DataTables too, and can even work inside an overflow: auto
container.
Craig, I refined your code a bit (among a few other things it's now using position:fixed) and wrapped it as a jQuery plugin.
Try it out here: http://jsfiddle.net/jmosbech/stFcx/
And get the source here: https://github.com/jmosbech/StickyTableHeaders
If you're targeting modern css3 compliant browsers (Browser support: https://caniuse.com/#feat=css-sticky) you can use position:sticky
, which doesn't require JS and won't break the table layout miss-aligning th and td of the same column. Nor does it require fixed column width to work properly.
Example for a single header row:
thead th
{
position: sticky;
top: 0px;
}
For theads with 1 or 2 rows, you can use something like this:
thead > :last-child th
{
position: sticky;
top: 30px; /* This is for all the the "th" elements in the second row, (in this casa is the last child element into the thead) */
}
thead > :first-child th
{
position: sticky;
top: 0px; /* This is for all the the "th" elements in the first child row */
}
You might need to play a bit with the top property of the last child changing the number of pixels to match the height of the first row (+ the margin + the border + the padding, if any), so the second row sticks just down bellow the first one.
Also both solutions work even if you have more than one table in the same page: the th
element of each one starts to be sticky when its top position is the one indicated into the css definition and just disappear when all the table scrolls down. So if there are more tables all work beautifully the same way.
Why to use last-child before and first-child after in the css?
Because css rules are rendered by the browser in the same order as you write them into the css file and because of this if you have just 1 row into the thead element the first row is simultaneously the last row too and the first-child rule need to override the last-child one. If not you will have an offset of the row 30 px from the top margin which I suppose you don't want to.
A known problem of position: sticky is that it doesn't work on thead elements or table rows: you must target th elements. Hopping this issue will be solved on future browser versions.