如何让多个 <tr> 元素同时粘在 table 上

How to have multiple <tr> elements sticky at once on a table

我正在开发一个有很多很长的表格的工具。其中一些表格在 <thead> 内有多行,我希望它们都立即成为 position: sticky。但是,我找不到执行此操作的方法。

我尝试将 position: sticky 添加到第 th,如下所示:

table thead th {
    position: sticky;
    top: 0;
}

我也尝试将 position: sticky 添加到整个 thead,但 Chromium 中似乎有 a bug 阻止了它的工作。

我正在努力实现这样的目标:

当用户滚动过去时,前两行都保持粘滞。

有没有在 Chrome 和 Firefox 中都有效的方法?我不需要支持IE。

如果所有 <tr> 元素都具有相同的高度,比如 20px,那么您可以尝试类似

thead tr th {
    position: sticky;
}

thead tr:nth-of-type(1) th {
    top: 0;
}

thead tr:nth-of-type(2) th {
    top: 20px;
}

thead tr:nth-of-type(3) th {
    top: 40px;
}