CSS 元素定位
Working with the "fixed" Value
每個元素都帶有 position 屬性,其預設值為 static,
可選用的值有 absolute、fixed、relative、sticky。
position: fixed;
以 viewpoint 為基準,使元素固定於指定位置。
常見應用情境為 Navbar
方位屬性
使用 top、right、bottom、left 可設定元素至參考基準的距離。
Understanding the Z-Index
使用 z-index 可調整元素的圖層位置,其預設值為 auto,也相當於 0。
z-index 屬性接受整數值,數值大的圖層堆疊於數值低的圖層之上。
z-index 在已套用 position 屬性的元素才會發揮作用。
兩個元素的 z-index 數值相同時,圖層位置取決於 DOM 的解析順序,
較晚解析者,其圖層位於較上層。
Adding a Badge to our Package
定位屬性 position 的值設為 absolute 時,該元素的位置取決於其親元素的定位設定。 若親元素的 position 為 static(預設值),absolute 將以 html 標籤為參考基準; 若親元素的 position 非 static,absolute 將以親元素為參考基準。
Diving Deeper into Relative Positioning
定位屬性 position 的值設為 relative 時,該元素將參考其自身在套用設定前的位置而位移。
以下列代碼為例,符合選擇器的元素在套用樣式後,將以原始位置基準,向下移動 20px。
p {
position: relative;
top: 20px;
}
Working with "overflow" and Relative Positioning
定位屬性 position 的值設為 relative 後,該元素的位置可能因定位設定而超出親元素的邊界。
此時可在親元素套用 overflow: hidden; 設定,如此一來,超出親元素邊界的部分將不會顯示。
如果套用 relative 設定的是 body 內的子元素,則需套用以下設定。
html,
body {
overflow: hidden;
}
Understanding the Stacking Context
z-index 屬性的差異只有在相同的 Stacking Context 才會顯現。
以下列代碼為例,由於 image 系列元素位於同一親元素之中,屬於同一 Stacking Context,
因此 z-index 值最高的 image-2 會位於圖層最上方。
然而,image 系列元素的親元素 headline 的 z-index 值比位於同一親元素的 contact-us 低,
因此無論 image 系列元素的 z-index 再怎麼高,其圖層位置也不會高過 contact-us。
<body>
<div class="navigation">navigation</div>
<div class="headline">
headline
<div class="image-1">image-1</div>
<div class="image-2">image-2</div>
<div class="image-3">image-3</div>
</div>
<div class="contact-us">contact-us</div>
</body>
.headline {
z-index: 1;
}
.contact-us {
z-index: 2;
}
.image-1 {
position: fixed;
z-index: 100;
}
.image-2 {
position: fixed;
z-index: 1000;
}
.image-3 {
position: fixed;
z-index: 10;
}
Useful Resources & Links
Positioning theory
More about the "position" property
The z-index
The Stacking Context
The "sticky" value and current browser support