CSS-Only Sticky Table Headers In Chrome

Donnie picture Donnie · May 16, 2017 · Viewed 62.6k times · Source

I have the following Sass snippet in which I want the <thead> to float as the table scrolls. This works properly in Safari, but not in Chrome Version 58.0.3029.110 (64-bit).

I know that Chrome has had on-again-off-again support for sticky, and currently supports it, but is it final? Is this a Chrome bug or do I need a different solution? (I prefer the CSS approach rather than Javascript because it's more performant.)

.table {
  thead {
    background: white;
    position: sticky;
    top: 0;
    z-index: 10;
  }
}

Answer

Kirill Matrosov picture Kirill Matrosov · May 16, 2017

position: sticky doesn't work with some table elements (thead/tr) in Chrome. You can move sticky to tds/ths of tr you need to be sticky. Like this:

.table {
  thead tr:nth-child(1) th{
    background: white;
    position: sticky;
    top: 0;
    z-index: 10;
  }
}

Also this will work.

.table {
    position: sticky;
    top: 0;
    z-index: 10;
}

You can move header to separate layout. For example:

<table class="table">
    <thead>
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>
    </tr>
    </thead>
</table>
<table>
    <tbody>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
</table>