: )
I know this question has been asked a lot, but I tried many solutions and just couldn't make it work properly.
I need to make the tbody of my table scrollable with fixed headers.
To start my table is built dynamically and is very large. 19 columns and about 800 rows.
First I worked with the jquery datatables plugin. After the table is in the container:
var tbl = createFilter('readDataTbl', '', condition);
$('#tableDiv').empty().append(tbl);
$('#readDataTbl').dataTable({
"scrollY": "200px",
"scrollCollapse": true,
"paging": false
});
but that creates a scroll in x and the headers are frozen like that:
Then I tried a css solution as follows:
<style>
table {
border-collapse: collapse;
width: 100%;
}
thead {
text-align:left;
display: table;
float: left;
width: 100%;
}
thead tr {
display: table-row;
width: 100%;
}
tbody {
display: block;
height: 120px;
overflow: auto;
float: left;
width: 100%;
}
tbody tr {
display: table;
width: 100%;
}
tbody tr {
height: 18px;
}
tbody td {
padding:1px 8px;
}
th, td {
width: 25%;
}
tr:after{ /* IE8 fix */
content: ".";
margin-left: -3px; /* to hide the content above tr */ /* not necessary if you are ok with 1px gap */
visibility: hidden;
}
</style>
But that just creates a mess in the tbody like that:
Then I tried thie method from Here adjusting the THs width after: css:
<style>
thead, tbody { display: block; }
tbody {
height: 100px; /* Just for the demo */
overflow-y: auto; /* Trigger vertical scroll */
overflow-x: hidden; /* Hide the horizontal scroll */
}
</style>
js:
var tbl = createFilter('readDataTbl', '', condition);
$('#tableDiv').empty().append(tbl);
var $table = $('table');
var $bodyCells = $table.find('tbody tr:first').children();
// Get the tbody columns width array
var 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]);
});
And then I noticed the THs long text made them bigger like that:
what could help me achieve my goal? Thought about inserting divs inside THs but not sure about it..
Thanks! : ]