Chrome 中仅 CSS 的粘性表格标题

新手上路,请多包涵

我有以下 Sass 片段,我希望 <thead> 在表格滚动时浮动。这在 Safari 中可以正常工作,但不能在 Chrome 中 Version 58.0.3029.110 (64-bit)

我知道 Chrome 已经断断续续地支持 sticky ,目前支持它,但它是最终的吗?这是 Chrome 错误还是我需要其他解决方案? (我更喜欢 CSS 方法而不是 Javascript,因为它的性能更高。)

 .table {
  thead {
    background: white;
    position: sticky;
    top: 0;
    z-index: 10;
  }
}

原文由 Donnie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 662
2 个回答

position: sticky 不适用于 Chrome 中的某些表格元素 (thead/tr)。您可以将粘性移动到需要粘性的 tr 的 tds/ths。像这样:

 .table {
  thead tr:nth-child(1) th{
    background: white;
    position: sticky;
    top: 0;
    z-index: 10;
  }
}

这也将起作用。

 .table {
    position: sticky;
    top: 0;
    z-index: 10;
}

您可以将标题移动到单独的布局。例如:

 <table class="table">
    <thead>
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>
    </tr>
    </thead>
</table>
<table>
    <tbody>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
</table>

原文由 Kirill Matrosov 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于仍在寻找解决方案并且对已接受的解决方案不满意的人。

1)在元素上使用sticky-top类。

2)有自己的班级

 th.sticky-header {
  position: sticky;
  top: 0;
  z-index: 10;
  /*To not have transparent background.
  background-color: white;*/
}
 <table class="table">
  <thead>
    <tr>
      <th class="sticky-header">1</th>
      <th class="sticky-header">2</th>
      <th class="sticky-header">3</th>
      <th class="sticky-header">4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </tbody>
</table>

原文由 Tomsgu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题