Css-Only Sticky Table Headers in Chrome

CSS-Only Sticky Table Headers In Chrome

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>

Sticky table head with css

I found the solution.

Chrome doesnt support sticky for thead/thr. So I moved the whole styling to each th element. Thats everything.

Found the solution here:
CSS-Only Sticky Table Headers In Chrome

Firefox/Chrome compatibility: HTML table with fixed header and column

Apparently, on Chrome, the "position:sticky" style does not work if it is attached to a tr tag, but it works if it is attached to a th or td. In Firefox, the style does work when attached to a tr.

Position sticky in table does not work in Firefox and Chrome 58

Like said here, Chrome still supports position sticky in table cells.

So a possible workaround is to point CSS to th instead of thead.

Please, see this sample: https://jsfiddle.net/owfmwdpm/

Border style do not work with sticky position element

The problem occurs because of the use of border-collapse: collapse. When browsers collapse the borders, the top and bottom border on the <th> must be getting applied to surrounding elements—the top border to the <table> and the bottom border to the following <tr>.

If you use border-collapse: separate and fashion your borders to sit on one side, the borders will truly attach to the <th>, stay fixed as expected, and appear collapsed.

Here are example styles that can be applied to your HTML snippet.

#wrapper {
width: 400px;
height: 200px;
overflow: auto;
}

table {
width: 100%;
text-align: center;
border-collapse: separate; /* Don't collapse */
border-spacing: 0;
}

table th {
/* Apply both top and bottom borders to the <th> */
border-top: 2px solid;
border-bottom: 2px solid;
border-right: 2px solid;
}

table td {
/* For cells, apply the border to one of each side only (right but not left, bottom but not top) */
border-bottom: 2px solid;
border-right: 2px solid;
}

table th:first-child,
table td:first-child {
/* Apply a left border on the first <td> or <th> in a row */
border-left: 2px solid;
}

table thead th {
position: sticky;
top: 0;
background-color: #edecec;
}


Related Topics



Leave a reply



Submit