0

I have a table of data using the < table> element inside a < div> element. The table needs to scroll vertically as needed and the header is to remain in place. Nothing too fancy!

Looking around the internet for examples on creating sticky headers I found a few examples that looked promising. I managed to pare things down to the following CSS -

thead th 
{ 
    position: sticky; 
    top: 0; 
}
    
th { 
    z-index: 1 
}

This works well. The only problem is that now there is a space at the bottom of the table that is scrollable. So the table in effect can be scrolled right off the top of the containing div. Here is a video -

See extra space after table reaches the bottom

As an aside, if I remove the "top: 0;" from the CSS the extra space disappears but the header is no longer sticky.

Does anybody have thoughts as to what I might need to do to not have the extra space at the bottom of the table? The other examples that I pulled from do not have this issue, but they are also not wrapped in a < div>. Do I need to do something with the < div> that is enclosing the table?

The CSS that I have for the < div> is as follows -

.applistscrollwrapper {
    width: 100%;
    min-height: 80px;
    max-height: 67vh;
    overflow-y: auto;
}

I have tried playing around with removing all or some of these attributes but I cannot get it working.

1 Answer 1

0

I recently had the same requirement - scrolling table with fixed headers.

I tried many solutions for fixing the header using styles like 'sticky', but I was never happy with the results.

In the end I split the header and body into separate tables and it works like a charm. You'll need to set a width for each column except the last one to ensure that the columns align.

<table>
    <thead>
        <tr>
            <th></th>
            <th></th>
            <th></th>
            ...
        </tr>
    </thead>
</table>
<div style="overflow: auto;">    
    <div style="position: relative;" onscroll={handleScroll}>
        <table>
            <tbody>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    ...
                </tr>
            </tbody>
        </table>
    </div>
</div>
1
  • I just spent a heap of time trying to do as suggested as although I struggle with the idea in principle.....I needed it to work! . It worked...except when it came to other functionality it fell a little flat. For example resizing the table caused problems as one table would adjust and the other wouldn't. Also, inline editing created problems for the same reason. Thanks for the response. Crossing my fingers others might have ideas.
    – Tom Ansley
    Mar 28, 2022 at 15:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .