719 字
4 分鐘
CSS sticky bottom: 0 不生效?先檢查工具列在正常流的位置
本文目錄
在可捲動的表單面板裡,工具列設了 position: sticky; bottom: 0,一載入卻留在面板上方。把工具列放到所屬區塊的內容後面,再使用 bottom: 0。 當工具列在正常流的位置低於捲動區的可見下緣時,sticky 才有理由把它往上推到邊緣。
量三個位置找出貼底的範圍
CSS Positioned Layout 規格用最近捲動容器的可見區域計算 sticky 的邊界。單設 bottom: 0 時,位於下緣外的工具列會往上偏移,偏移範圍仍受自身包含區塊約束。已在可見區上方的工具列會留在原位。這個差異在同一份 HTML 裡就能量到。CSSWG Sticky positioning
儲存下列內容為 HTML 並開啟,按「量測」。範例先量工具列放在區塊開頭的結果,再把同一個節點移到區塊末端。每次都量工具列下緣相對於面板上緣的距離。
<!doctype html><html lang="zh-Hant"><meta charset="utf-8"><title>Sticky bottom 量測</title><style> #panel { height: 180px; overflow: auto; background: #f3f0fa; } .content { height: 360px; } #actions { position: sticky; bottom: 0; height: 40px; background: wheat; } .next { height: 160px; background: #dbedf7; }</style><button id="measure" type="button">量測</button><div id="panel"> <section id="editor"> <div id="actions"><button type="button">儲存</button></div> <div class="content">編輯區內容</div> </section> <div class="next">下一區</div></div><pre id="result"></pre><script> const panel = document.querySelector('#panel'); const editor = document.querySelector('#editor'); const actions = document.querySelector('#actions');
function sample(scrollTop) { panel.scrollTop = scrollTop; return actions.getBoundingClientRect().bottom - panel.getBoundingClientRect().top; }
document.querySelector('#measure').onclick = () => { editor.prepend(actions); const first = sample(0); editor.append(actions); const last = [0, 240, 380].map(sample); panel.scrollTop = 0; document.querySelector('#result').textContent = JSON.stringify({ first, last }); };</script>在這份高 180px 的面板裡,工具列放在開頭時,下緣距離 40px。移到末端後,捲動量為 0、240、380px 時,下緣距離分別為 180、160、20px。第一次剛好貼底。第二次工具列的正常位置已進入可見區。捲到下一區時,工具列跟著編輯區離開。
依照工具列要跟著誰移動來選版面
- 只在某一段內容內貼底。 將工具列放在該段內容後面,再設定 sticky。捲到下一段時,確認它隨原區塊離開。
- 整個面板捲動時都看得到。 讓內容區單獨捲動,工具列當它的同層元素。例如面板用有高度上限的 Grid,設定
grid-template-rows: minmax(0, 1fr) auto,內容區用overflow: auto。 - 固定在整頁視窗底部。 使用
position: fixed,並替末端內容保留工具列所占的空間。行動裝置還要確認底部安全區域。 - 短頁尾端對齊畫面底部,長頁照常捲。 用有最小高度的欄向 Flex 版面,讓主要內容用
flex: 1吃掉剩餘空間,頁尾留在正常流中。
若工具列已放在內容後方,仍跟著整頁滑走,先在 DevTools 確認哪個元素的 scrollTop 隨操作變動,再檢查祖先的 computed overflow。
參考資料:
CSS sticky bottom: 0 不生效?先檢查工具列在正常流的位置
https://laplusda.com/posts/css-sticky-bottom-not-working/