首页 > 解决方案 > 网格内溢出自动内的粘性表格标题

问题描述

已经发布了类似的问题,但这是对该问题的新看法。

到目前为止我所知道的

我的问题是上下文

问题

https://jsfiddle.net/jw147aqk/1/

您需要调整窗口大小以使表格溢出。

* {
  padding: 0;
  margin: 0;
}

html, body {
  height: 100%;
}

.wrap {
  background: #eee;
  height: 100%;
  
  display: grid;
  grid-template-rows: 50px 1fr 50px;
  grid-template-areas: "header" "main" "footer";
}

header {
  grid-area: header;
  background: green;
  color: #fff;
}

main {
  overflow-y: auto;
}

footer {
  grid-area: footer;
  background: #ba0000;
  color: #fff;
}

table {
  width: calc(100% - 3px);
  border-collapse: collapse;
}

table th {
  background: #000;
  color: #fff;
  height: 50px;
  position: sticky;
}

table td {
  background: #fff;
  height: 50px;
  border: 1px solid #ccc;
}
<div class="wrap">
  <header>My header</header>
  <main>
    <table>
      <thead>
        <tr>
          <th>Head first</th>
          <th>Head second</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
        <tr>
          <td>Cell first</td>
          <td>Cell second</td>
        </tr>
      </tbody>
    </table>
  </main>
  <footer>Footer</footer>
</div>

标签: csshtml-tablesticky

解决方案


添加top: 0;表中

table th {
  background: #000;
  color: #fff;
  height: 50px;
  position: sticky;
  top: 0;
}

推荐阅读