I have a table that is too long to fit in its container. I have set overflow-x:auto on the parent element so you can scroll along and see all of the values in the table. Now, I want the first two columns of the table to stick to the left-hand side of the container. I can set position:sticky on these cells, which works fine except I have to specify the point at which they stick. If I don't know the width of the first column then can I still stick the second column next to it? Setting left:0 on both columns will make them overlap, which is undesirable.
What I want is the first and second column side-by-side as they initially appear but they stay there as the user scrolls along the table. I would have grouped the cells together into one sticky element but this isn't allowed by the HTML specification (tr can only have td/th children). Ideally I want to set something like "left:initial" that would make each element stick at the position it starts at.
How could I best implement this using CSS?
.container {
overflow-x: auto;
width: 100px;
}
.stick {
position: sticky;
left: 0px;
}
<div class="container">
<table>
<thead>
<tr>
<th class="stick">Team</th>
<th class="stick">Name</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>...</th>
</tr>
</thead>
<tbody>
<tr>
<td class="stick">Blue</td>
<td class="stick">Gary</td>
<td>8</td>
<td>12</td>
<td>4</td>
<td>0</td>
<td>...</td>
</tr>
<tr>
<td class="stick">Red</td>
<td class="stick">Sam</td>
<td>7</td>
<td>11</td>
<td>5</td>
<td>2</td>
<td>...</td>
</tr>
<tr>
<td class="stick">Red</td>
<td class="stick">Joe</td>
<td>2</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>