將容器 line-height 設定為與 height 相同數值,即可讓單行文字垂直置中:
.nav-item {
height: 2em; /* 容器高度 */
line-height: 2em; /* 行高等於容器高度 */
/* 文字自動垂直置中 */
}
line-height 決定行框高度,文字在行框內垂直置中。.parent {
display: flex;
align-items: center; /* 垂直置中 */
justify-content: center; /* 水平置中 */
height: 200px;
}
.parent {
display: grid;
place-items: center; /* 同時垂直水平置中 */
height: 200px;
}
.parent { position: relative; height: 200px; }
.child {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
.parent {
display: table-cell;
vertical-align: middle;
height: 200px;
}
| 場景 | 推薦方案 | IE 支援 |
|---|---|---|
| 單行文字(導航、按鈕) | line-height = height | 全版本 |
| 多行文字/區塊(現代專案) | Flexbox | IE10+ |
| 需支援 IE9 | Absolute + Transform | IE9+ |
| 需支援 IE8 | Table-cell | IE8+ |
| 未知高度容器 | Flexbox / Grid | IE10+ |
line-height = height 是單行文字垂直置中最簡潔、相容性最好的方案。多行或區塊置中請改用 Flexbox(首選)、Grid 或 Absolute+Transform,根據專案瀏覽器支援需求選擇。