【问题标题】:Sticky table head with css带有 css 的粘性表头
【发布时间】:2018-07-25 22:13:27
【问题描述】:

目前我正在使用以下 html + css 来获取我的粘性表头:

<html>
<body>
  <table class="table table-striped" style="display: block;">
      <thead style="position: sticky;top:6.833rem;; background-color: #e5e5e5;z-index: 10;">
          <tr>
              <th>Heading 1</th>
              <th>Long Heading  </th>
              <th>Heading 2</th>
              <th>Very Very Very Very Long Heading</th>
              <th>Very Long Heading</th>
          </tr>
      </thead>
      <tbody style="table-layout: fixed;">
          <tr>
              <td>Content</td>
              <td>Content</td>
              <td>Content</td>
              <td>Content</td>
              <td>Content</td>
          </tr>
      </tbody>
  </table>
</body>
</html>

这在 Firefox 中运行良好。但是当我在 Chrome 中运行相同的代码时,thead 不再具有粘性。

如果我添加

display: block;

到它工作的样式,但是我的标题和我的内容列的宽度不再相同了。

有什么建议吗?

【问题讨论】:

    标签: css html-table sticky


    【解决方案1】:

    这应该清楚地说明如何使用粘性。也许您必须根据需要调整尺寸。为了便于说明,我还在两者之间放置了一个填充 div。

    table {
      top: 50px;
      position: sticky;
      background-color: #e5e5e5;
    }
    
    body{
      height: 2000px;
    }
    
    #fill{
      height: 150px;
      width: 100%;
    }
     <div id="fill"></div>
      <table>
          <thead >
              <tr>
                  <th>Heading 1</th>
                  <th>Long Heading  </th>
                  <th>Heading 2</th>
                  <th>Very Very Very Very Long Heading</th>
                  <th>Very Long Heading</th>
              </tr>
          </thead>
          <tbody style="table-layout: fixed;">
              <tr>
                  <td>Content</td>
                  <td>Content</td>
                  <td>Content</td>
                  <td>Content</td>
                  <td>Content</td>
              </tr>
          </tbody>
      </table>

    请注意,我给主体设置了一个高度,以表明它会在您滚动时粘住。

    【讨论】:

    • fixed 的问题是,我不想修复thead。它应该滚动直到我到达它应该停留的点(从顶部开始 6.833rem)。这适用于我的解决方案,但仅限于 Firefox。
    • 好的,我会调查的
    【解决方案2】:

    我找到了解决办法。

    Chrome 不支持thead/thr 的粘性。因此,我将整个样式移至每个元素。就是这样。

    在这里找到解决方案: CSS-Only Sticky Table Headers In Chrome

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 2021-09-06
      相关资源
      最近更新 更多