C. Greene C. Greene - 6 months ago 8
HTML Question

How to keep a tables height contained within a parent div

I cannot figure out how to keep this tables height contained within the containing div. My goal is to be able to scroll in order to see it all. There are plenty of solutions to solve this when dealing with the width, but I have not been able to get them working with the height.

<html>

<head>
<style>
.container {
border: 1px solid black;
height: 100px;
}

td {
font-size: 40px;
}

table {
table-layout: fixed;
height: 100%;
overflow-y: scroll;
}
</style>
</head>

<body>
<div class="container">
<table>
<thead>
<tr>
<th>
header
</th>
<th>
header
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
data
</td>
<td>
data
</td>
</tr>
<tr>
<td>
data
</td>
<td>
data
</td>
</tr>
<tr>
<td>
data
</td>
<td>
data
</td>
</tr>
</tbody>
</table>
</div>
</body>

</html>


https://jsfiddle.net/meeow314159/3vs9bmsf/

Answer

        .container {
            border: 1px solid black;
            height: 100px;
            overflow-y: scroll;
        }

        td {
            font-size: 40px;
        }

        table {
            table-layout: fixed;
            height: 100%;
        }
<div class="container">
  <table>
    <thead>
      <tr>
        <th>
          header
        </th>
        <th>
          header
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          data
        </td>
        <td>
          data
        </td>
      </tr>
      <tr>
        <td>
          data
        </td>
        <td>
          data
        </td>
      </tr>
      <tr>
        <td>
          data
        </td>
        <td>
          data
        </td>
      </tr>
    </tbody>
  </table>
</div>

You were almost there. The overflow-y needs to be applied to the parent container with the height set on it, not the table itself. Hope this helps.