position: relative(或 absolute/fixed),建立定位基準,不脫離文檔流。position: absolute,配合 top/right/bottom/left 相對父層定位。<div class="parent">
<div class="child">固定在父層右上角</div>
父層其他內容...
</div>
.parent { position: relative; width: 500px; height: 300px; background: #0f0; margin: 0 auto; }
.child { position: absolute; top: 30px; right: 20px; width: 200px; height: 80px; background: #f00; z-index: 10; }
若子元素使用 position: fixed,定位基準變為**視口**,而非父層。此時:
left/right 失效(相對視口),改用 margin-left/margin-right 配合 left: 50% 等技巧。absolute + 父層 relative 維持相對定位關係。同一父層內,z-index 決定前後關係;若父層本身有 z-index,會形成新的堆疊上下文,子元素 z-index 僅在該上下文內比較。
position: relative(預設 static 不建立基準)。top/right/bottom/left 而非 margin 定位(fixed 除外)。width/height 或讓內容撐開,避免塌陷。box-sizing: border-box 讓邊框/內距計算直觀。