Take the 2-minute tour ×

By generalizing the code in this SO answer, I've created a small jQuery plug-in which makes it easy to set up a scrolling header on any table - that is, when you scroll down such that the table header would normally be outside of the viewable window, a clone of the header becomes fixed to the top of the window so that you can see which columns are which. That's all working fine, but the problem I'm having is that I can't get the column widths to match up perfectly between the clone table and the original table.

I've created a jsFiddle which demonstrates the problem here. The gist of it is that I'm using the following loop to copy cell widths from the parent table to the clone table:

$("#tbl1").find('tr').first().children().each(function(i, e)

This is necessary because the clone table only consists of the parent table's header; it has none of the content, therefore its column widths would be different than the parent table's without this step. However, this loop doesn't quite work properly. The cell widths in the cloned table are always off by a few pixels. This happens in both IE8 and Chrome (and presumably others, though I haven't tested them.)

I'm at a complete loss as to how to correct this problem. Please check out the jsFiddle, as it explains the problem much better than I have.

It's perhaps worth noting that the same code seems to work when the clone table's position is not fixed. However, that's of no use to me, since I need it to be fixed.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

For some reason, the width attribute on your cloned table is throwing off the calculations. I'm not exactly sure why but if you use:


at the end of your jquery code like, here, it seems to work.

share|improve this answer
That does appear to have done it. Thank you so much! I'll award you the bounty as soon as SO allows me to do so. –  Mitch Lindgren Mar 28 '11 at 4:56
The issue still exists if you set border as 1px for the cells th,td { border: 1px solid black; } you can tell the gap from jsFiddle –  Roy Ling Nov 30 '12 at 11:44
Sorry, update the link of jsFiddle –  Roy Ling Nov 30 '12 at 12:03
add comment

Try using offsetWidth, something like...

    // make each cell width in the header table, the same width as
    // the cells in the orginal table (header table has one row)  
    $headerTable.find('td, th').each(function(index)
        var width = originalTable.rows[0].cells[index].offsetWidth
        this.width = width;
share|improve this answer
Thanks for the suggestion, but it did not appear to have any effect. Am I doing it correctly? jsfiddle.net/YVMKu/5 –  Mitch Lindgren Mar 25 '11 at 22:55
add comment

Your Answer


