萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 容器相對定位:讓子元素相對父層定位

核心原理

父元素設定 position:relative (或 absolute/fixed/sticky) 建立**定位上下文**,子元素 position:absolute 時,top/right/bottom/left 即相對於**最近的已定位祖先**而非 body。

最小範例

<div id="container" style="position:relative; width:400px; height:300px; border:1px solid #ccc;">
  <div id="nav" style="position:absolute; left:30px; top:5px; background:#1976d2; color:#fff; padding:.5rem 1rem;">
    導航欄 (相對 container 定位)
  </div>
</div>

定位上下文建立條件

  • position: relative | absolute | fixed | sticky
  • transform / filter / perspective / clip-path / mask / contain 等非 none 值
  • will-change 指定上述屬性
  • Flex/Grid 容器 (子項 position:absolute 時)

常見應用場景

  • 下拉選單:父 relative,子 absolute; top:100%; left:0。
  • Tooltip / Popover:同理,配合 JS 計算座標。
  • 圖片熱區/標註:容器 relative,標籤 absolute 百分比座標。
  • Modal 置中:fixed 相對視窗,或 absolute 相對 relative 容器。

陷阱與注意

  1. 未設定父層定位 → 子元素相對 body 或 html 定位,導致位置錯亂。
  2. Transform 建立新上下文:.parent{transform:translateZ(0)} 會讓內部 fixed 子元素相對父層而非視窗定位 (規格規定)。
  3. Z-index 陷阱:定位元素會建立堆疊上下文,子元素 z-index 只在該上下文內比較。
  4. 百分比高度:父層必須有明確高度,子元素 height:100% 才生效。

除錯技巧

/* 開發時暫時加上,視覺化定位上下文 */
*[style*="position:relative"],
*[style*="position:absolute"],
*[style*="position:fixed"] {
  outline: 1px dashed red;
}
copyright © 萬盛學電腦網 all rights reserved