HittmanA HittmanA - 28 days ago 10
HTML Question

Cross-browser compatible scrollable table

I am trying to make a table that takes up 50% of the screen. However, if there is more info than the table can hold, it should be scrollable. I have been trying many different ways to do this, but none I have found worked. It needs to be cross-browser compatible with all modern browsers and preferably older browsers to. How can I do this? Thanks in advance!

Note: I am using w3.css

Some code I have tried:



table {
height: 100px;
overflow-y: scroll;
}

<table class="w3-table-all">
<thead>
<tr class="w3-red">
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody>
</table>





I have tried doing that but it still doesn't work. I also tried various combinations thereof, styling the tbody, tr, td, etc. None showed a scrollbar

Answer

First put your table inside a div then put your specified height and the overflow to the class of that div so that it will become scrollable.

CSS

.table-scroll {
  border: 1px solid #000;
  width:50%;
  height: 100px;
  overflow-y: scroll;
}

HTML

<div class="table-scroll">
<table class="w3-table-all">
<thead>
  <tr class="w3-red">
    <th>First Name</th>
    <th>Last Name</th>
    <th>Points</th>
  </tr>
</thead>
<tbody>
<tr>
  <td>Jill</td>
  <td>Smith</td>
  <td>50</td>
</tr>
<tr>
  <td>Eve</td>
  <td>Jackson</td>
  <td>94</td>
</tr>
<tr>
  <td>Adam</td>
  <td>Johnson</td>
  <td>67</td>
</tr>
</tbody>
</table>
</div>

Here is a reference in jsfiddle.