LESSON-11 · TOPIC 01
sticky 與祖先 overflow 能找出 sticky 的實際 scroll container,並判斷祖先 overflow 如何改變黏附範圍。
code-edit 定位、堆疊與錨點|sticky 與祖先 overflow 本頁只練一個責任
Starter Checkpoint Solution 本頁只練什麼 能找出 sticky 的實際 scroll container,並判斷祖先 overflow 如何改變黏附範圍。
sticky 失效常不是 z-index 太小,而是沒有捲動空間、缺少 inset,或祖先建立了另一個 scrolling mechanism。
要修改的檔案: files/starter/style.css
定位: 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。|依 starter-1 定位,只修改「sticky 與祖先 overflow」的責任。
任務情境 先結果,再原理;完成後要能說出自己看見的證據。
現在的問題 側欄標題設 sticky 卻沒有留在預期位置,頁面同時有一個 overflow:auto 面板。
起始狀態: 面板可局部捲動;標題 position:static,尚未套 top:0 sticky。
完成後要看到 computed position 由 static 變 sticky;scrollTop 增加後 sticky top 留在 container top 附近且不超出祖先範圍。
驗收證據: 現有 runtime before=static、after=sticky;required facts 包含 scrollTop、targetTop、containerTop
何時會用到 章節導覽、表格標題或頁內工具列需要在局部捲動區停留時。
常見混淆: position:fixed 相對 viewport,sticky 仍保留 normal-flow 空間並受 containing block 邊界限制。
觀念與最小範例 這段程式是理解起點,不是要你直接跳過 Starter。
sticky 與祖先 overflow Sticky positioning and ancestor overflow sticky 會在自己的捲動容器裡黏住,不一定黏在整個瀏覽器視窗。
正式說法: A sticky positioned box is offset relative to its nearest ancestor with a scrolling mechanism and its containing block;an inset such as top is required to establish the sticky threshold。
.scroll-panel{overflow:auto;max-height:12rem}.panel-title{position:sticky;top:0}複製這段
三步完成本主題 每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。
Step 1|先看見目前缺口,不急著貼答案。 檔案: files/starter/style.css 定位: 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。
要做: 先重新載入 Starter,記錄目前畫面、DOM、Computed、Console 或文件內容。
預期: 能指出「由 sticky 元素往上找第一個 overflow 非 visible 的祖先。」目前的缺口。
證據: 保存 files/starter/style.css 的目前狀態,並指出下一步只會修改哪個檔案責任。
卡住先查: 確認開啟的是 files/starter/style.css,且定位到 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。。
Step 2|只修改本主題的一個責任。 檔案: files/starter/style.css 定位: 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。
要做: 執行實驗切換 sticky-active class,讀取 position;完整 probe 再捲動 data-sticky-root 並量 targetTop/containerTop。
預期: computed position 由 static 變 sticky;scrollTop 增加後 sticky top 留在 container top 附近且不超出祖先範圍。
證據: 現有 runtime before=static、after=sticky;required facts 包含 scrollTop、targetTop、containerTop
卡住先查: 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。
Step 3|重新載入並以證據驗收,不以『看起來差不多』判定完成。 檔案: files/starter/style.css 定位: 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。
要做: 重新整理頁面,再逐項比對預期結果與 evidence。
預期: computed position 由 static 變 sticky;scrollTop 增加後 sticky top 留在 container top 附近且不超出祖先範圍。
證據: 現有 runtime before=static、after=sticky;required facts 包含 scrollTop、targetTop、containerTop
卡住先查: 由 sticky 元素往上找第一個 overflow 非 visible 的祖先。
觀察示範 這個示範只讓你看懂概念,不會替你修改 Starter,也不會自動宣告完成。
sticky 與祖先 overflow runtime fixture · read-only demo
驗收證據 勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。
提示 1|方向 先確認哪個元素真的在捲動。
提示 2|關鍵片段 目標加 position:sticky 與 top:0,祖先需有足夠內容可捲。
提示 3|完整解答與原因 完整解答與原因:overflow:auto 祖先是 scroll container;捲動後 sticky 依 top:0 留在其上緣,離開祖先邊界後不再黏住。