div {
position: static; /* 預設值 */
top: 50px; /* 無效 */
left: 100px; /* 無效 */
}
.relative-box {
position: relative;
top: 20px; /* 向下移動 20px */
left: 30px; /* 向右移動 30px */
}
✅ 注意: 相對定位會保留元素原本的空間,不影響其他元素!
.container {
position: relative; /* 設為參考點 */
width: 500px;
height: 300px;
}
.absolute-box {
position: absolute;
top: 50px;
left: 50px;
}
✅ 注意: 如果 .absolute-box 沒有 relative 父級,它會參考 body!
.fixed-box {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: black;
color: white;
}
✅ 注意: 滾動網頁時,.fixed-box 仍然固定在頂部!
.sticky-box {
position: sticky;
top: 10px;
background-color: yellow;
}
✅ 注意: 當滾動超過 10px,元素就會固定在 10px 的位置!
定位方式 | 脫離文檔流 | 相對於誰 | 影響其他元素 | 主要應用 |
---|---|---|---|---|
static | ❌ 否 | 無 | ✅ 會影響 | 預設排列 |
relative | ❌ 否 | 自己原本的位置 | ✅ 會影響 | 微調、父級參考點 |
absolute | ✅ 是 | 最近的 relative/absolute/fixed 父級 | ❌ 不影響 | 彈窗、浮動區塊 |
fixed | ✅ 是 | 視窗(viewport) | ❌ 不影響 | 固定導覽列、回頂部按鈕 |
sticky | ❌/✅ 部分脫離 | 最近的可滾動祖先 | ✅ 會影響 | 表頭固定、導航欄 |