CSS 垂直置中歷來是面試必考、實戰常見痛點,因為塊級元素預設無垂直置中機制,且 vertical-align 僅對 inline/inline-block/table-cell 生效。
| 方法 | 適用元素 | 需知高度 | 瀏覽器支援 | 優點 | 缺點 |
|---|---|---|---|---|---|
| line-height = height | 單行文字 / inline-element | 是 (容器固定高) | 全瀏覽器 | 極簡、無副作用 | 多行文字失效、容器高度固定 |
| padding 上下相等 | 單行/多行 非替換元素 | 否 (內容撐開) | 全瀏覽器 | 無需固定高度、語意清晰 | 無法精確置中於固定高容器 |
| Flexbox | Flex Container 子元素 | 否 | IE10+ | 單行/多行/未知高度皆完美、可水平同時置中 | 需父層 display:flex |
| Grid | Grid Container 子元素 | 否 | IE10+ (前綴) | place-items:center 一行搞定、二維對齊 |
較重、IE 需前綴 |
| Absolute + Transform | Absolute/Fixed 定位元素 | 否 | IE10+ | 不需父層配合、可動畫、脫離文檔流 | 建立堆疊上下文、可能模糊 |
| Table-cell + vertical-align | Table-cell 子元素 | 否 (但容器需高度) | IE8+ | IE8 相容、語意接近表格 | 破壞語意、響應式難控制 |
.tag {
height: 32px;
line-height: 32px; /* 等於 height */
padding: 0 12px;
border-radius: 16px;
background: #eee;
}
.flex-v-center {
display: flex;
align-items: center; /* 垂直置中 */
justify-content: center; /* 水平置中 (可選) */
min-height: 200px; /* 容器最小高度 */
}
.grid-v-center {
display: grid;
place-items: center; /* align-items + justify-items */
min-height: 200px;
}
.modal {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
/* 無需寬高,自適應內容 */
max-width: 90vw;
max-height: 90vh;
overflow: auto;
}
.table-v-center {
display: table;
width: 100%;
height: 200px;
}
.table-v-center > .cell {
display: table-cell;
vertical-align: middle;
text-align: center;
}
place-items: center 最簡潔。line-height 或 padding 最輕量。align/justify-items,勿混用。transform: translate(-50%, -50%) 可能導致文字模糊,加 transform-style: preserve-3d 或將內容再包一層 transform: translateZ(0)。height: 100%、top: 50% 失效。確保父鏈有高度或用 min-height: 100vh。垂直置中不再是謎題,根據元素類型、佈局上下文、瀏覽器需求選對法則,一次到位。更多 CSS 佈局核心技巧,請持續關注本站系列文章。