1

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>
dashingdove
  • 304
  • 1
  • 4
  • 15
  • for the second column you need to use left:Xpx where X is the width of the first column – Temani Afif Aug 03 '20 at 10:25
  • Sorry, I should have specified that the width of the columns is not fixed. The code snippet I provided is only to illustrate what I'm describing. – dashingdove Aug 03 '20 at 10:27
  • Do you want to prevent the overlap that's happening between columns? Is that the issue? – jaimish11 Aug 03 '20 at 10:37
  • Yes, I want the two columns to appear side-by-side, not overlapped. – dashingdove Aug 03 '20 at 10:44
  • You can check this answer: https://stackoverflow.com/questions/1312236/how-do-i-create-an-html-table-with-a-fixed-frozen-left-column-and-a-scrollable-b – Jacob Aug 03 '20 at 13:01

0 Answers0