HTML Tables with Fixed Header on Scroll using position: sticky

Use-Cases of this code snippet

  • Know how to create a HTML table whose header becomes fixed on scrolling (pure CSS, no Javascript).

Persistent headers on HTML tables can be achieved using position:sticky CSS property on the <thead> element.

Making table header row fixed on page scrolling was once quite a complicated problem that was somehow achieved with Javascript. But now it can be achieved easily with 2 lines of CSS.

Demo

View Demo

Download Codes

HTML

<table>
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tr>
        <td>Value</td>
        <td>Value</td>
        <td>Value</td>
    </tr>
    <tr>
        <td>Value</td>
        <td>Value</td>
        <td>Value</td>
    </tr>
</table>

CSS

thead {
    position: sticky;
    top: 0;
}

Notes

  • Using border-collapse: collapse and giving borders to <th> and <td> will not work with sticky positioning. To achieve this we need to use border-collapse: separate and apply borders on <th> / <td> on appropriate sides.
Loading Comments