Fixed header table, scrollable body to occupy 100%

2019-02-28 06:34发布

问题:

I have a table which I effectively want to have a fixed header and allow the rows in the table to be scrolled through while the header row remains static. In addition, I want the body section of the table to take up the remaining height in the containing element that is left after the header row is rendered.

So far I have two tables, the first contains a thead, tr and multiple th, the second contains the tbody with multiple tr each with multiple td, like so:

<table>
    <thead>
        <tr>
            <th>Heading 1</th>
            <th>Heading 2</th>
            <th>Heading 3</th>
            <th>Heading 4</th>
            <th>Heading 5</th>
        </tr>
    </thead>
</table>
<div style="overflow:scroll">
    <table>
        <tbody>
            <tr><td /><td /><td /><td /><td /></tr>
            <tr><td /><td /><td /><td /><td /></tr>
        </tbody>
    </table>
</div>

I've done some research and found out that setting a style up as follows on a DIV makes it scale to the height of its containing element

position:absolute;
height:auto;
top:0;
bottom:0;

The problem is that setting a position of absolute on both the table containing the header and the table containing the body sets them to render at 0, 0 within the containing element. I could specifiy a pixel value for the CSS top property but this makes it more rigid.

Is there some key CSS positioning value or combination that I'm not thinking of that could help me achieve all of this?

回答1:

I could specifiy a pixel value for the CSS top property but this makes it more rigid.

Yes, but this is what you want, isn't it?

That's really the only solution.