1
thead{
width: calc(100% - 17px);
display:block;
}

tbody{
display:block;
overflow-y: auto;
height:100px;
}

http://jsfiddle.net/mkgBx/

I can adjust width of thead to match that of tbody + scrollbar. However, in cases when scrollbar is not displayed, tbody stretches further to the right. Is there any way to fix tbody width?

Arman Ospanov
  • 143
  • 1
  • 1
  • 9

4 Answers4

2

I don't think you can set the tbodys width to ignore the presence of the scrollbar. Would a change to the structure of the mark-up be acceptable?

CSS

table{
    font: 11px arial;
    width: 245px;
}
th, td{
    border:1px solid #000;
}
div {
    height:90px;
    width: 262px; /*table width + 17px */
    overflow-y: auto;    
}

HTML

<table>
    <thead>
        <tr>
            <th style="width:165px">Name</th>
            <th>Country</th>
        </tr>
    </thead>
</table>
<div>
    <table>
        <tbody>
            <tr>
                <td style="width:165px">Mart Poom</td>
                <td>Estonia</td>
            </tr>
            <tr>
                <td>David Loria</td>
                <td>Kazakhstan</td>
            </tr>
            <tr>
                <td>Wojciech Szczęsny</td>
                <td>Poland</td>
            </tr>
            <tr>
                <td>Gianluigi Buffon</td>
                <td>Italy</td>
            </tr>
            <tr>
                <td>Igor Akinfeev</td>
                <td>Russia</td>
            </tr>
        </tbody>
    </table>
</div>

http://jsfiddle.net/nF2NL/1/

This allows the div to provide the scrolling and the table to remain a set width.

Jonathan
  • 1,833
  • 13
  • 15
0

I would not explicitly declare the <tbody> and <thead> tags for your table, as this is unnecessary. One solution to your problem would be to make the row (<tr>) of <th>s position: fixed. Someone else had a similar problem here: How to make a tables header static when scrolling

Community
  • 1
  • 1
Adrian Roworth
  • 813
  • 1
  • 7
  • 16
0

You need to use JavaScript to handle this. Check if the scrollbar appears and adjust the width of the tbody accordingly.

Here's the JS code relevant to this where t is the tbody element:

if (t.clientHeight == t.scrollHeight)
{
    t.style.width = "224px";
}

I've modified your JSFiddle to show you how it can work in your case.

Chirag Bhatia - chirag64
  • 4,430
  • 3
  • 26
  • 35
-2

with width 100% it adapts to the table with, doesn't matter if it has a scroll or not.

thead{
    width: 100%;
    display:block;
}