Chrome中仅支持CSS的粘性表标题

Don*_*nie 38 css google-chrome sass

我有以下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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*sov 61

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

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

这也行.

.table {
    position: sticky;
    top: 0;
    z-index: 10;
}
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,如果表包含在`overflow:auto`或`overflow-x:auto`的元素中,这将不起作用.如果在bootstrap的`.table-responsive`类中包装表,就会发生这种情况. (15认同)
  • 如果列的宽度相同,则单独的布局选项才可用 (13认同)
  • 我同意 Rick Viscomi 关于单独布局选项仅当列的宽度都相同时才可行,并且如果表格之后还有其他内容,该解决方案也并非没有缺点,因为整个内容的粘性表格甚至在结束之后第二个表包含内容,因此在大多数情况下无法使用。可以在以下地址看到关于 jfiddle 的示例:https://jsfiddle.net/eg6s4097/1/ 以及所有提到的缺点 (2认同)

Tom*_*sgu 30

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

1)在元素上使用粘性顶级类.

2)有自己的班级

th.sticky-header {
  position: sticky;
  top: 0;
  z-index: 10;
  /*To not have transparent background.
  background-color: white;*/
}
Run Code Online (Sandbox Code Playgroud)

  • 如果`thead`中有两个(或更多)标题行怎么办? (4认同)

Car*_*Car 8

您可以在标题表格单元格而不是表格行上设置粘性位置。

.td.header {
  position: sticky;
  top:0px;
}
Run Code Online (Sandbox Code Playgroud)

查看这个jsfiddle的简单示例。