Reputation: 137
I am having trouble to fix the header of a table, here is my issue:
I used the same code from this post: Table header to stay fixed at the top when user scrolls it out of view with jQuery
It is almost working, but the problem is the width of the header changed when I scroll down.
I wonder what I am doing wrong. I tried the following code to fix the width, but does not work.
$("#header-fixed td").each(function(index){
var index2 = index;
$(this).width(function(index2){
return $("#table-1 td").eq(index).width();
});
});
Here is the link: http://vvb.me/test.html
Upvotes: 1
Views: 1732
Reputation: 12869
The width of table cells is determined by not only the content of that particular table cell, but also the other cells in the same vertical column as it. This is because tables form blocks so the widths of the columns must line up.
What's happening here is that the calculated width of your attached thead
cells is different from the widths calculated for your detached, fixed thead
cells.
In the attached thead
, the widths of the cells are largely determined by the data below. In the second instance, which isn't attached to the tbody
, the width is solely determined by the header td
s.
One solution would be to specify the width of the cells in both theads
. As an example, specifying,
<td style='...; width: 50px;'>
on all of your thead
cells would make them equal.
You could also use javascript to determine the width of each attached thead
cell and set the bottom thead
cells to be equal to their corresponding cell. Calculating the dimensions of DOM elements can be done with Javascript/Jquery. Check out answers like this one for methods on how to do that.
Upvotes: 1