CSS 無直接「垂直靠底對齊」屬性(vertical-align 僅針對行內/表格單元格)。需在固定高度容器底部精準定位文字。
<div id="txt">
<p>底部對齊的文字</p>
</div>
#txt {
position: relative; /* 關鍵:建立定位基準 */
width: 300px;
height: 300px;
border: 1px solid #333;
text-align: center; /* 水平置中 */
}
#txt p {
position: absolute; /* 脫離文檔流 */
bottom: 0; /* 靠近容器底部 */
left: 0; right: 0; /* 水平撐滿 */
margin: 0; padding: 0; /* 重置預設間距 */
}
| 屬性 | 作用 | 注意事項 |
|---|---|---|
| position: relative | 容器成為定位基準,不脫離文檔流 | 不影響佈局,無副作用 |
| position: absolute | 子元素相對最近的 relative/absolute/fixed 祖先定位 | 脫離文檔流,不佔空間 |
| bottom: 0 | 距離容器底部邊緣 0 | 可改為 10px 等產生間距 |
| left: 0; right: 0 | 水平撐滿容器,配合 text-align:center 實現水平置中 | 比 margin:auto 更穩健 |
#txt p {
position: absolute;
bottom: 20px; left: 20px; right: 20px;
line-height: 1.6;
/* 文字多行時自動向上擴展,底部邊緣固定 */
}
#txt {
display: flex;
flex-direction: column;
justify-content: flex-end; /* 主軸末端對齊 = 底部 */
min-height: 300px; /* 避免內容撐高 */
padding: 20px;
box-sizing: border-box;
}
/* 子元素無需額外樣式,自動靠底 */
#txt {
display: grid;
align-content: end; /* 內容區塊靠底 */
min-height: 300px;
}
| 方案 | 支援度 | 代碼量 | 靈活度 | 推薦場景 |
|---|---|---|---|---|
| Relative + Absolute | IE6+ | 中 | 高(像素級控制) | 舊專案、精確像素控制、需兼容古老瀏覽器 |
| Flexbox | IE10+ | 少 | 高(響應式友善) | 現代專案首選 |
| Grid | IE10+ (部分) | 極少 | 極高 | 複雜二維佈局中的底部對齊 |
position: relative → 子元素相對 body 定位left: 0; right: 0 → 寬度塌縮為內容寬,無法水平置中bottom: 0 失效(相對於內容高度而非視覺高度)Relative + Absolute 是經典且通用的底部對齊方案,精確控制像素級距離。現代專案優先選擇 Flexbox/Grid,代碼更簡潔、響應式更自然、無脫流副作用。理解三種方案的原理與適用邊界,才能在不同約束下做出最佳選擇。