position:sticky實現(xiàn)表頭固定

單詞 sticky 的中文意思是“粘性的”,position:sticky 表現(xiàn)也符合這個粘性的表現(xiàn)?;旧希梢钥闯鍪?position:relative 和 position:fixed 的結(jié)合體。當(dāng)元素在屏幕內(nèi),表現(xiàn)為 relative,就要滾出顯示器屏幕的時候,表現(xiàn)為 fixed。例如,可以標題吸頂。

其中導(dǎo)航元素設(shè)置了如下CSS:
nav?{position:?sticky;top: 0;}
于是,正如大家看到,隨著頁面的滾動,當(dāng)導(dǎo)航距離上邊緣 0 距離的時候,黏在了上邊緣,表現(xiàn)如同 position:fixed。
我們可以實現(xiàn)富有層次的滾動交互,比如下面:

.container {width: 100%;max-height: 500px;overflow: auto;}h4 {position: sticky;top: 0;background: green;}.content {width: 100%;height: 500px;background: red;}<body><div class="container"><div><h4>蘋果h4><div class="content">1div>div><div><h4>香蕉h4><div class="content">2div>div><div><h4>葡萄h4><div class="content">3div>div>div>body>
我們還可以實現(xiàn)表頭固定,類似于下面的效果:

<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Documenttitle><style>* {margin: 0;padding: 0;}html,body {width: 100%;height: 100%;}table {font-family: "Fraunces", serif;font-size: 125%;white-space: nowrap;margin: 0;border: none;border-collapse: separate;border-spacing: 0;table-layout: fixed;border: 1px solid black;}table td,table th {border: 1px solid black;padding: 0.5rem 1rem;}table thead th {padding: 3px;position: sticky;top: 0;z-index: 1;width: 25vw;background: white;}table td {background: #fff;padding: 4px 5px;text-align: center;}table tbody th {font-weight: 100;font-style: italic;text-align: left;position: relative;}table thead th:first-child {position: sticky;left: 0;z-index: 2;}table tbody th {position: sticky;left: 0;background: white;z-index: 1;}.container {/* 表格最大寬度和高度 */width: 100%;max-height: 500px;overflow: auto;}style>head><body><div class="container"><table><thead><tr><th>用戶姓名th><th>用戶年齡th><th>用戶學(xué)校th><th>用戶班級th><th>用戶成績th><th>用戶個數(shù)th>tr>thead><tbody><tr><th>張三th><td>1td><td>2td><td>3td><td>4td><td>5td>tr><tr><th>張三th><td>1td><td>2td><td>3td><td>4td><td>5td>tr>tbody>table>div>body>html>
總結(jié):
元素根據(jù)正常文檔流進行定位,然后相對它的最近滾動祖先(nearest scrolling ancestor)和 containing block (最近塊級祖先 nearest block-level ancestor),包括 table-related 元素,基于 top, right, bottom, 和 left 的值進行偏移。偏移值不會影響任何其他元素的位置。
該值總是創(chuàng)建一個新的層疊上下文(stacking context)。注意,一個 sticky 元素會“固定”在離它最近的一個擁有“滾動機制”的祖先上(當(dāng)該祖先的 overflow 是 hidden, scroll, auto, 或 overlay 時),即便這個祖先不是最近的真實可滾動祖先。這有效地抑制了任何“sticky”行為。
評論
圖片
表情
