Skip to content

Table With Fixed Header

See article  in stackoverflow forum duplicated here.

In order to make <tbody> element scrollable, we need to change the way it’s displayed on the page i.e. using display: block; to display that as a block level element.

Since we change the display property of tbody, we should change that property for thead element as well to prevent from breaking the table layout.

So we have:

thead, tbody {
display
: block;
}
tbody
{
height
:100px;/* Just for the demo */
overflow-y: auto;/* Trigger vertical scroll */
overflow-x: hidden;/* Hide the horizontal scroll */
}

Web browsers display the thead and tbody elements as row-group (table-header-group and table-row-group) by default.

Once we change that, the inside tr elements doesn’t fill the entire space of their container.

In order to fix that, we have to calculate the width of tbody columns and apply the corresponding value to the thead columns via JavaScript.

Auto Width Columns

Here is the jQuery version of above logic:

// Change the selector if needed
var $table = $('table'),
$bodyCells
= $table.find('tbody tr:first').children(),
colWidth
;

// Get the tbody columns width array
colWidth
= $bodyCells.map(function(){
return $(this).width();
}).get();

// Set the width of thead columns
$table
.find('thead tr').children().each(function(i, v){
$
(v).width(colWidth[i]);
});

 

Tags: