570 字
3 分鐘

CSS position: fixed 跟著頁面捲動?檢查祖先的 transform

本文目錄

側欄加入滑入動畫後,原本固定在視窗角落的按鈕跟著頁面捲走。用 DevTools 往上檢查祖先的 transform。即使算出的位移是零,transform: translateX(0) 仍會替後代的固定定位建立包含區塊,按鈕的偏移量便改以該祖先的 padding box 為基準。 CSS Transforms:變形的繪製模型

用兩顆按鈕找出定位基準#

存成 HTML 後捲動頁面。兩顆按鈕都用 position: fixed 和 top: 12px,只有第一顆在帶有 transform 的區塊內。

<!doctype html>
<meta charset="utf-8">
<title>固定定位的包含區塊</title>
<style>
body { margin: 0; min-height: 150vh; }
.card {
margin: 100px 24px 0;
padding: 48px 16px;
background: #dbeafe;
transform: translateX(0);
}
.action { position: fixed; top: 12px; }
.inside { left: 12px; }
.outside { right: 12px; }
</style>
<div class="card">
動畫容器
<button class="action inside" type="button">卡片裡</button>
</div>
<button class="action outside" type="button">卡片外</button>

在 DevTools Console 量兩顆按鈕。先從頁面頂端量一次,再向下捲動後執行同一行。

console.table([...document.querySelectorAll('.action')].map(button => ({
label: button.textContent,
top: button.getBoundingClientRect().top,
})));

卡片裡的 top 應隨頁面捲動減少,卡片外的值維持 12。接著在 Styles 面板停用 .card 的 transform,重複量測。兩顆按鈕這時都應維持在視窗上緣 12px。用 Chrome 瀏覽器 158 版(2026 年 11 月的正式版)實際捲過 40px:卡片內的按鈕從 112px 移到 72px,外側始終是 12px。若真實頁面停用某一層後還是會移動,繼續往外找其他會建立包含區塊的祖先。規格也列出 will-change、contain 等可能的來源,請以實際設定和量測縮小範圍。 CSS Positioned Layout:包含區塊

要貼住視窗還是卡片?#

  • 要持續貼住視窗時,把浮動按鈕搬到動畫容器外。若外層容器還有其他定位條件,可以另外留一個靠近應用程式根節點的浮層容器,並在搬動後重新測試定位與焦點順序。
  • 要貼住卡片時,在卡片設定 position: relative,按鈕使用 position: absolute。即使日後拿掉卡片動畫,按鈕仍有明確的定位基準。
  • 要求元素在某段內容捲到邊界時才黏住,先確認是否適合 position: sticky 與捲動容器 的行為。

參考資料:

W3C:CSS Transforms 的 transform rendering model

W3C:CSS Positioned Layout 的 containing blocks

CSS position: fixed 跟著頁面捲動?檢查祖先的 transform
https://laplusda.com/posts/css-position-fixed-transform-parent/
作者
Zero
發佈於
2026-11-26
許可協議
CC BY-NC-SA 4.0