CSS position 定位
position 屬性用來控制元素的定位方式,是 CSS 佈局中非常重要的屬性。
position: static(預設)
元素按照正常的文件流排列,不受 top、right、bottom、left 影響。
.box {
position: static; /* 預設值 */
}
position: relative
元素相對於「自己原本的位置」偏移,但原本的空間仍然保留。
.box {
position: relative;
top: 20px; /* 往下偏移 20px */
left: 10px; /* 往右偏移 10px */
}
- 元素會相對於原本位置移動
- 原本的空間會保留,不會影響其他元素
- 常用於作為
position: absolute子元素的定位參考
position: absolute
元素脫離正常文件流,相對於「最近的定位祖先」定位。
.parent {
position: relative; /* 作為定位參考 */
}
.child {
position: absolute;
top: 0;
right: 0;
}
- 元素會脫離文件流,不佔據空間
- 相對於最近的
position不是static的祖先元素定位 - 如果沒有定位祖先,則相對於
<html>定位 - 常用於製作覆蓋層、徽章、關閉按鈕等
定位參考
/* 子元素會相對於 .parent 定位 */
.parent {
position: relative;
}
.badge {
position: absolute;
top: -10px;
right: -10px;
}
position: fixed
元素脫離正常文件流,相對於「瀏覽器視窗」定位,捲動頁面時位置不變。
.navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
.back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
}
- 相對於視窗定位,不隨頁面捲動
- 常用於固定導航列、返回頂部按鈕、浮動廣告等
position: sticky
元素在捲動到特定位置前是 relative,之後變成 fixed。
.header {
position: sticky;
top: 0; /* 當捲動到頂部時固定 */
}
.sidebar-item {
position: sticky;
top: 80px; /* 距離頂部 80px 時固定 */
}
- 結合了 relative 和 fixed 的特性
- 需要指定 top、right、bottom、left 其中之一
- 常用於固定表頭、黏性側邊欄等
- 父元素需要有足夠的高度才會生效
定位屬性 (top, right, bottom, left)
這四個屬性用來指定元素的偏移位置:
.box {
position: absolute;
top: 20px; /* 距離上方 20px */
right: 10px; /* 距離右方 10px */
bottom: 30px; /* 距離下方 30px */
left: 40px; /* 距離左方 40px */
}
填滿父元素
.overlay {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
/* 或使用 inset 簡寫 */
.overlay {
position: absolute;
inset: 0;
}
比較表
| position | 脫離文件流 | 定位參考 | 用途 |
|---|---|---|---|
| static | 否 | - | 預設值 |
| relative | 否 | 自己原本位置 | 微調位置、作為子元素定位參考 |
| absolute | 是 | 最近定位祖先 | 覆蓋層、徽章、彈出選單 |
| fixed | 是 | 視窗 | 固定導航、浮動按鈕 |
| sticky | 部分 | 滾動容器 | 黏性標題、固定側邊欄 |
實用範例
徽章
.avatar-container {
position: relative;
display: inline-block;
}
.badge {
position: absolute;
top: -5px;
right: -5px;
background: red;
color: white;
border-radius: 50%;
padding: 2px 6px;
font-size: 12px;
}
卡片上的標籤
.card {
position: relative;
}
.card-tag {
position: absolute;
top: 10px;
left: 10px;
background: rgba(0,0,0,0.7);
color: white;
padding: 4px 8px;
}
固定導航列
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 60px;
background: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
z-index: 100;
}
body {
padding-top: 60px; /* 為固定導航留空間 */
}
全螢幕覆蓋層
.overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
z-index: 1000;
}
黏性側邊欄
.sidebar {
position: sticky;
top: 80px;
height: fit-content;
}
置中(absolute)
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}