| 場景 | 特徵 | 推薦方案 |
|---|---|---|
| 單行文本 | 高度固定、單行 | line-height = height |
| 多行文本/未知高度 | 內容動態、高度不定 | Flex / Grid / Table-cell |
| 圖片/媒體元素 | 替換元素、固有尺寸 | Flex / Grid / absolute + transform |
| 模態框/彈層 | 全屏居中、疊加上下文 | Flex + fixed / Grid + place-items |
.flex-center {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
min-height: 100vh; /* 容器最小高度 */
}
/* 單行代碼版 */
.flex-center { display: flex; place-items: center; min-height: 100vh; }
優勢:語義清晰、支援動態內容、無副作用、易於擴展多欄佈局。
.grid-center {
display: grid;
place-items: center; /* 同時水平垂直居中 */
min-height: 100vh;
}
/* 精確控制區域 */
.grid-center {
display: grid;
grid-template-rows: 1fr auto 1fr; /* 上中下三區,中間自適應 */
}
.content { grid-row: 2; }
.table-center {
display: table;
width: 100%;
height: 100vh;
}
.table-center > .cell {
display: table-cell;
vertical-align: middle;
text-align: center; /* 水平居中需配合 text-align */
}
結構要求:包裹層 display: table、內層 display: table-cell。
.absolute-center {
position: relative; /* 父元素建立定位上下文 */
min-height: 100vh;
}
.absolute-center > .content {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%); /* 關鍵:基於自身尺寸偏移 50% */
}
核心原理:top/left: 50% 基於父元素,translate(-50%, -50%) 基於自身,完美抵消。
.margin-auto-center {
position: relative;
height: 300px; /* 父元素必須有高度 */
}
.margin-auto-center > .box {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
width: 300px; height: 200px; /* 必須固定寬高 */
margin: auto; /* 關鍵:四方向 auto 平均分配剩餘空間 */
}
.inline-center {
line-height: 200px; /* 容器固定高度 */
text-align: center; /* 水平居中 */
font-size: 0; /* 消除字體大小影響 */
}
.inline-center > * {
display: inline-block;
vertical-align: middle;
font-size: 1rem; /* 恢復字體大小 */
line-height: 1.5; /* 恢復行高 */
}
/* 幽靈元素法 (無需固定高度) */
.ghost-center::before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.ghost-center > * {
display: inline-block;
vertical-align: middle;
}
.writing-mode-center {
writing-mode: vertical-lr; /* 垂直書寫模式 */
text-align: center; /* 主軸居中 = 原垂直方向 */
}
.writing-mode-center > * {
writing-mode: horizontal-tb; /* 內容恢復橫向 */
display: inline-block;
text-align: center;
}
需要支援 IE8/9? → 是 → Table-cell / Absolute+Transform
↓ 否
內容高度固定? → 是 → Line-height / Absolute+Margin-auto
↓ 否
現代項目? → 是 → Flex (place-items) / Grid (place-items)
↓ 否
組件庫/通用庫? → 考慮兼容性矩陣,提供多種實現
.multiline-clamp-center {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* 最多 3 行 */
overflow: hidden;
/* 垂直居中技巧:結合 Flex */
display: flex;
align-items: center;
min-height: 4.5rem; /* 3 * 1.5rem line-height */
}
position: absolute + 負 margin(需知尺寸)、display: table (語義汙染、渲染較慢)現代 CSS 開發中,display: flex; place-items: center 是 95% 場景的最優解。僅在極舊環境或極特殊約束下退而求其次。掌握所有方案原理,是為了在受限環境中做出最佳技術決策。