1

I'd like to create a table in html. The table should take the height of it's parent (100%) so that the scrollbar is at the bottom (X). Tbody should be scrollable (Y) and take the width of it's parent (100%). As of now, Tbody width is more than 100% (td?). Th and td should be in one line. Th should take the width of the td so every row is the same.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
}

.wrap {
  height: 100%;
  border: 1px solid blue;
}

table {
  width: 100%;
  height: 100%;
  border-collapse: collapse;
  overflow-x: auto;
  border: 1px solid red;
}

th {
  text-align: left;
}

tbody {
  overflow-y: auto;
  height: 125px;
  border: 1px solid orange;
  display: block;
 
}

tr {
  display: table;
  table-layout: fixed;
  width: 100%;
}

th {
  border: 1px solid red;
  width: 100px;
}

th:nth-child(2n+1) {
  background-color: green;
  width: 200px;
}
<div class="wrap">
  <table>
  <thead>
    <tr>
      <th>H_a</th>
      <th>H_b</th>
      <th>H_c</th>
      <th>H_d</th>
      <th>H_e</th>
      <th>H_a</th>
      <th>H_b</th>
      <th>H_c</th>
      <th>H_d</th>
      <th>H_e</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
      <td>e</td>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
      <td>e</td>
    </tr>
     <tr>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
      <td>e</td>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
      <td>e</td>
    </tr>
     <tr>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
      <td>e</td>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
      <td>e</td>
    </tr>
  </tbody>
</table>
</div>
Mr. Potter
  • 85
  • 7

1 Answers1

0

You can add overflow:scroll and display:block to always display a horizontal scrollbar in your table:
Add horizontal scrollbar to html table

If you only want to display a scrollbar when necessary, use overflow:auto; instead.

To make all column widths the same, use table-layout: fixed;

Felix Schildmann
  • 574
  • 1
  • 7
  • 22
  • I've used `table-layout: fixed` but it doesn't work. I definitely got something wrong there. Look at the snippet above. – Mr. Potter May 20 '20 at 07:06
  • 1
    you have programmed it to set width 200px on alternate th. `th:nth-child(2n+1) { background-color: green; width: 200px; }` – yinsweet May 20 '20 at 11:57
  • @yinsweet Sure, but the td should always take the width of the upper th (e.g. td1 = th1, td2 = th2, td3 = th3 etc.). I thought "Table layout: fixed" would solve this. – Mr. Potter May 20 '20 at 12:56