该答案将用作不完全支持的占位符position: sticky
,并将随着时间的推移而更新。当前建议不要在生产环境中使用本机实现。
有关当前支持,请参见此:https :
//caniuse.com/#feat=css-sticky
用于 position: sticky
另一种答案是使用
position: sticky。如W3C所述:
粘性放置的框的位置类似于相对放置的框,但偏移量是使用滚动框参照最近的祖先,如果没有祖先具有滚动框,则参照视口进行计算。
这恰好描述了相对静态头的行为。将其分配给
<thead>或第一个
<tr>HTML标签将很容易,因为W3C应当支持此标签。但是,Chrome,IE和Edge都无法为这些标签分配粘性位置属性。目前,解决这一问题似乎也没有优先考虑。
对于表格元素似乎起作用的是将sticky属性分配给表格单元。在这种情况下,
<th>单元格。
因为表不是尊重您为其分配的静态大小的块元素,所以最好使用 包装器元素 来定义滚动溢出。
编码
div { display: inline-block; height: 150px; overflow: auto}table th { position: -webkit-sticky; position: sticky; top: 0;}table { border-collapse: collapse;}th { background-color: #1976D2; color: #fff;}th,td { padding: 1em .5em;}table tr { color: #212121;}table tr:nth-child(odd) { background-color: #BBDEFB;}<div> <table border="0"> <thead> <tr> <th>head1</th> <th>head2</th> <th>head3</th> <th>head4</th> </tr> </thead> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> </table></div>在此示例中,我使用一个简单的
<div>包装器来定义滚动高度(静态高度为)
150px。当然可以是任何大小。现在已经定义了滚动框,粘性
<th>元素将“与滚动框最靠近的祖先”作为核心。
使用position: sticky
polyfill
不支持的设备可以使用polyfill,该polyfill通过代码实现行为。粘性位就是一个例子,它的行为类似于浏览器的实现
position:sticky。
polyfill的示例: http :
//jsfiddle.net/7UZA4/6957/



