理解 position 的關鍵在於「相對於誰定位」:
<div class="banner">
<img src="banner.jpg" alt="横幅圖片" class="banner-img">
<div class="banner-content">
<h3>標題文字</h3>
<p>描述內容...</p>
</div>
</div>
.banner {
position: relative; /* 關鍵:建立定位上下文 */
width: 100%;
max-width: 800px;
margin: 20px auto;
overflow: hidden; /* 容納浮動/絕對定位子元素 */
border-radius: 8px;
}
.banner-img {
display: block;
width: 100%;
height: auto;
}
.banner-content {
position: absolute; /* 相對 .banner 定位 */
left: 0; right: 0; bottom: 0; /* 底部滿寬貼合 */
padding: 20px;
color: #fff;
font-size: 1.5rem;
line-height: 1.5;
font-weight: 600;
background: rgba(0, 0, 0, 0.15); /* 半透明黑背景 */
/* 現代漸變背景增強可讀性 */
background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
}
| 屬性 | 相對於 | 脫離文檔流 | 佔據空間 | 典型用途 |
|---|---|---|---|---|
| static | 正常流 | 否 | 是 | 默認佈局 |
| relative | 自身原位置 | 否(視覺偏移) | 是 | 微調位置、建立定位上下文 |
| absolute | 最近定位祖先 | 是 | 否 | 彈層、標籤、圖標精確定位 |
| fixed | 視窗 viewport | 是 | 否 | 導航欄、回頂部、模態遮罩 |
| sticky | 視窗+父容器 | 否→是 | 是→否 | 吸頂表頭、側邊欄跟隨 |
.centered {
position: absolute;
/* 法一:margin auto(需寬高固定) */
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
width: 200px; height: 100px;
/* 法二:transform(尺寸不固定,推薦) */
top: 50%; left: 50%;
transform: translate(-50%, -50%);
/* 法三:flex 父容器 */
/* 父容器: display: flex; justify-content: center; align-items: center; */
/* 法四:grid 父容器 */
/* 父容器: display: grid; place-items: center; */
}
position: relative/absolute/fixed/sticky + z-index (非 auto) 會創建層疊上下文opacity < 1、transform、filter、will-change 也會創建層疊上下文.responsive-banner {
position: relative;
}
@media (max-width: 768px) {
.banner-content {
position: static; /* 移動端改為文檔流,避免遮擋內容 */
background: rgba(0,0,0,0.6);
margin-top: 12px;
}
}
relativerelative,子加 absolutefixedstickymargin: 0 auto (block) 或 text-align: center (inline)