昨天我們用 display 把東西乖乖排好,像是在叫大家「排隊、站好」。
但你有沒有遇過這種情況:
光靠 display 沒辦法,這時候就需要定位 (position)。
---> position 就像是把元素放到「指定的椅子」上
今天我們會一步步把 position 玩懂,最後再順便看看老前輩 float
簡單來說,position 決定「這個元素是乖乖跟著文件排?還是我說怎樣就怎樣?」
常見值有這幾個:
HTML
<div class="container">
<div class="box normal">Static普通區塊</div>
<div class="box relative">Relative 區塊</div>
<div class="box absolute">Absolute 區塊</div>
<div class="box fixed">Fixed 區塊</div>
</div>
CSS
.container {
position: relative; /* 讓裡面的 absolute 有定位依據 */
height: 300px;
border: 1px solid #ccc;
}
.box {
width: 100px;
height: 100px;
background: #ffd6a5;
margin: 10px;
}
.relative {
position: relative;
top: 20px; /* 往下移動 */
left: 100px;
background: #caffbf;
}
.absolute {
position: absolute;
top: 10px;
right: 10px;
background: #9bf6ff;
}
.fixed {
position: fixed;
bottom: 10px;
right: 10px;
background: #ffadad;
}
fixed 永遠黏在右下角,absolute 則乖乖待在 container 的右上角
讓標題滾動到頂部時「停住」:
h2 {
position: sticky;
top: 0;
background: white;
}
滾動頁面時,可以發現標題碰到視窗頂端就「黏住」
float
原本用來讓文字繞圖
img {
float: left; /* 圖片靠左,文字繞排 */
margin: 0 10px 10px 0;
}
.clearfix::after {
content: "";
display: block;
clear: both; /* 清除浮動影響 */
}
用空間佔位來理解