I have a HTML table with a header that I am locking to the top of my browser with jQuery once the user has scrolled down past it. I've seen a lot of solutions to this particular problem on SO and elsewhere, but cannot get past a roadblock I've hit.
I have been able to get my jQuery to lock the header fine (I have a < tr > within my < thead > containing my column headers, and I've given that < tr > an ID of "theadTrId").
$(document).ready(function () {
var widths = new Array();
//create array of <th> widths
var i = 0;
$('th').each(function () {
widths[i] = $(this).width();
i++;
});
var elementPosTop = $('#theadTrId').offset().top;
$(window).scroll(function () {
SetWidths();
});
var SetWidths = function () {
var wintop = $(window).scrollTop();
if (wintop > elementPosTop) {
$('#theadTrId').css({ "position": "fixed", "top": "0" });
//<th> and <td> widths in 1st column
$('#th1').width(widths[0]);
$('#td1').width(widths[0]);
//<th> and <td> widths in 2nd column
$('#th2').width(widths[1]);
$('#td2').width(widths[1]);
//x number of other columns with same logic...
} else {
$('#theadTrId').css({ "position": "inherit" });
}
};
});
This works fine and locks the header to the top of the window when scrolling down and puts it back to default when scrolling back up, but for the life of me I cannot get the < th > and < td > column widths to line up when the following CSS is added:
td {
max-width: 200px;
}
td, th {
padding: 10px;
}
Should I remove that styling, all headers and their columns line up perfectly. This styling is required and cannot be removed. Table width also needs to be set at 100%. Any suggestions?
jsFiddle here (you can see desired behavior if you delete the last 2 CSS properties, issue is most pronounced in Firefox): http://jsfiddle.net/aKe6j/59/