On horizontal scroll for a table, how can I have sticky th until reach the next th?

I have a table with a horizontal scrollbar. I need to make the data of the first two rows sticky when horizontally scroll the table.
This is the table at the first place:

enter image description here

When I scroll I want “2016” and “Dec” to be displayed until I reach “2017” and “Jan”, and the same for 2017 and Jan until I reach the next date.
This is the picture while scrolling:

enter image description here

and the picture when I reach the next date:

enter image description here

Please note that I don’t want numbers to be sticky.
I already used scrollToFixed library for vertical scroll, but i’m not sure if it works in my situation.
Any hints will be appreciated.

1 thought on “On horizontal scroll for a table, how can I have sticky th until reach the next th?”

  1. You can do it using only css with position: sticky.

    Note:

    • Putting .sticky on both th and the text to have the effect like this:
      enter image description here
    • If you don’t want the text to be cut, just remove class sticky on th.
    .sticky {
      position: sticky;
      left: 0;
    }
    .table-wrapper {
      max-width: 200px;
      overflow-x: auto;
    }
    td {
      min-width: 40px;
    }
    th {
      padding: 0 5px;
      background-color: white;
      text-align: left;
    }
    <div class="table-wrapper">
      <table>
        <thead>
          <tr>
            <th class="sticky" colspan="10">
              <span class="sticky">2016</span>
            </th>
            <th class="sticky" colspan="10">
               <span class="sticky">2017</span>
            </th>
          </tr>
          <tr>
            <th class="sticky" colspan="10">
              <span class="sticky">Dec</span>
            </th>
            <th class="sticky" colspan="10">
              <span class="sticky">Jan</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
            <td>6</td>
            <td>7</td>
            <td>8</td>
            <td>9</td>
            <td>10</td>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
            <td>6</td>
            <td>7</td>
            <td>8</td>
            <td>9</td>
            <td>10</td>
          </tr>
        </tbody>
      </table>
    </div>
    Reply

Leave a Comment