user425445
user425445

Reputation:

How do I align columns in thead and tbody when tbody css display attribute is block

I have a table with thead, tbody and tfoot.
The css value for display is block - enables adding a scrollbar to the body and scroll the rows while the thead and tfoot stay in place.
The TD tags widths are not fixed as the tables width changes according to the width of the TD.
I would like to align the thead's TH tags with the tbody's TD tags.

How can this be done? (CSS or JQuery)

Edit:
The target browser is Google - Chrome!
And adding a slight twist, the Table is RTL.

The CSS:

tbody{
    display: block;
    overflow: auto;
}

thead, tfoot{
    display: block;
}

The HTML:

    <table>
        <caption>My Table</caption>
        <thead>    
            <tr><th>Col1</th><th>Col2</th></tr>
        </thead>
        <tbody>    
            <tr><td>Cell11</td><td>Cell12</td></tr>
            <tr><td>Cell21</td><td>Cell22</td></tr>
            <tr><td>Cell31</td><td>Cell32</td></tr>
            <tr><td>Cell41</td><td>Cell42</td></tr>
            <tr><td>Cell51</td><td>Cell52</td></tr>
            <tr><td>Cell61 Is Wide</td><td>Cell62</td></tr>
        </tbody>
        <tfoot>
            <tr><th>6 Rows</th><th></th></tr>
        </tfoot>                
    </table>

You can try it using this jsFiddle.

Thanks and be happy.

Upvotes: 7

Views: 9601

Answers (2)

Phrogz
Phrogz

Reputation: 303401

Use JS or jQuery to access the offsetWidth of the cells in the first row of the tbody and then set those as explicit width styles for the th. You can iterate the row in the tbody and head in unison by using the index from one iteration to access the element in the other.

Upvotes: 4

Ahmed Magdy
Ahmed Magdy

Reputation: 6040

overflow for tbody is not supported by all browsers!!

Update: you might have to create min. two tables for the headers and one for the content and put the second on inside div and use overflow and you have to sync the columns width using javascipt.

Upvotes: 1

Related Questions