具有固定标题的表-tbody在我的表中溢出thead

时间:2019-08-13 15:26:54

标签: html css sass

我正在尝试在表中添加一个修复标头,并且我设法进行了一半。确实,我可以滚动内容,但是tbody溢出了thead。我发现了许多关于stackoverflow的问题,我尝试了许多问题,但没有成功...

已更新 并且在页边距顶部时,tbody会在我滚动时显示在页边距顶部

这是我的代码:

.fixed-header {
  overflow-x: hidden;
  overflow-y: auto;
  height: 250px;
}

table {
  color: black;
  max-height: 750px;
  margin-top: 31px;
  width: 100%;
}

thead {
  background-color: #505d66;
}

th {
  position: sticky;
  top: 31px;
}

tbody {
  background-color: grey;
}

tbody tr td {
  padding-top: 10px;
  padding-bottom: 10px;
}
<div class="fixed-header">
  <table>
    <thead>
      <tr>
        <th>COL</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>

    </tbody>
  </table>
</div>

1 个答案:

答案 0 :(得分:1)

正如@acesmndr所说,只需将背景色放在TH

.fixed-header {
  margin-top: 30px;
  overflow-x: hidden;
  overflow-y: auto;
  height: 250px;
}

table {
  color: black;
  max-height: 750px;
  width: 100%;
}

thead {
  background-color: #505d66;
}

th {
  position: sticky;
  top: 0px;
  background-color: #505d66;
}

tbody {
  background-color: grey;
}

tbody tr td {
  padding-top: 10px;
  padding-bottom: 10px;
}
<div class="fixed-header">
  <table cellpadding="0" cellspacing="0">
    <thead>
      <tr>
        <th>COL</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>
      <tr>
        <td>ITEM</td>
      </tr>

    </tbody>
  </table>
</div>