Goal: Have a table with sticky headers and able to scroll horizontally when the table is to wide for the window.
Using the code below it is possible to achieve both of these goals, but not at the same time. When div1 has overflow-x: auto; it stops position: sticky; working.
Any ideas on how to have these both work at the same time?
table {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
text-align: left;
position: relative;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f1f1f1}
th {
background: darkblue;
color: white;
position: sticky;
top: 0;
box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
}
#div1 {
overflow-x: auto;
}
<h2>Table with sticky headers and overflow-x?</h2>
<div id="div1">
<table>
<tr>
<th>Person</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
<th>Longheader</th>
</tr>
<tr>
<td>A</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
</tr>
<tr>
<td>B</td>
<td>25</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
<td>24</td>
</tr>
<tr>
<td>C</td>
<td>33</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
</tr>
</table>