views:

240

answers:

2

I've this sample table and I want to make header row of table visible all the time. Header row should scroll with horizontal scrollbar and shouldn't scroll with vertical scrollbar.

table:

<div style="width:800px; height:150px;overflow:scroll;margin:50px auto;">
<table style="width:1600px" border="1">
    <thead style="">
      <tr>
        <th style="width:800px">id_1</th>
        <th style="width:800px">id_2</th>
      </tr>
    </thead>
    <tbody style="">
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
    </tbody>
</table>
</div>

How can I do this with css only? Suggestions in this and this thread didn't seem to work, possibly due to presence of scrollbars.

EDIT

I'm looking for a css solution. Table structure and layout can't be changed. Other than this there is no restriction on html.

A: 

You can use CSS's position:fixed coupled with some other properties to achieve that.

See this for more information.

Sarfraz
position:fixed won't work because header has to scroll with horizontal scrollbar.
understack
A: 

Try this, using 2 divs

<div style="width:800px; margin:0 0 0 0;">
<table  width="800" border="1" cellpadding="3">
    <thead style="">
      <tr>
        <th style="width:400px">id_11</th>
        <th style="width:400px">id_2</th>
      </tr>
    </thead>
</table>
</div>
<div style="width:820px; height:150px;overflow:scroll;margin:0 0 0 0; overflow-x: hidden;">
<table  width="800" border="1" cellpadding="3">
    <tbody style="">
      <tr><td style="width:400px">1200</td><td style="width:400px">1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
      <tr><td>1200</td><td>1200</td></tr>
    </tbody>
</table>
</div>

alt text

jeph perro
I just tested it and it looks good.
jeph perro
@jeph perro: unfortunately I can't use this work around since in my case thead has to be present inside table to make other javascript things work. Besides column width in your case is 400px which has to be 800px. It makes a special case because total table width in my case is 1600px which is wider than my screen. Hence horizontal scrollbar is always required.
understack
Remove overflow-x: hidden;
jeph perro