tbody vertical scrollbar is only visible after horizontal scrolling

Viewed 16

When the horizontal scrollbar is to the left, the vertical scrollbar is not present

enter image description here

When the horizontal scrollbar is to the right, the scrollbar is present

enter image description here

How can I make the vertical scrollbar show at all times (it should only cover tbody)

Here's the Stackblitz

And here's the code anyway:

table thead,
table tbody {
  display: block;
}

tbody {
  height: 160px;
  overflow: auto;
}

div {
  width: 160px;
  overflow: auto;
}
<div>
  <table>
    <thead>
      <tr>
        <th>Title 1</th>
        <th>Title 2</th>
        <th>Title 3</th>
        <th>Title 4</th>
        <th>Title 5</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
    </tbody>
  </table>
</div>

1 Answers

Leave out overflow: auto; from tbody, and add position: sticky; to thead. Make sure to add a background-color to thead so the table's content doesn't overlap when scrolling.

table thead,
table tbody {
  display: block;
}

thead {
  position: sticky;
  top: 0;
  background: white;
}

tbody {
  height: 160px;
  /* overflow: auto; */
}

div {
  width: 160px;
  overflow: auto;
}
<div>
  <table>
    <thead>
      <tr>
        <th>Title 1</th>
        <th>Title 2</th>
        <th>Title 3</th>
        <th>Title 4</th>
        <th>Title 5</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
        <td>Data 4</td>
        <td>Data 5</td>
      </tr>
    </tbody>
  </table>
</div>

Related