萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 垂直置中技巧:line-height 等於 height 單行文字解法

單行文字垂直置中核心技巧

將容器 line-height 設定為與 height 相同數值,即可讓單行文字垂直置中:

.nav-item {
    height: 2em;          /* 容器高度 */
    line-height: 2em;     /* 行高等於容器高度 */
    /* 文字自動垂直置中 */
}

原理解析

  • line-height 決定行框高度,文字在行框內垂直置中。
  • 當行框高度 = 容器高度,文字視覺上即在容器正中。
  • 僅適用於單行文字,多行文字會導致行距過大、版面破裂。

多行文字 / 區塊元素垂直置中現代方案

Flexbox(推薦,IE10+)

.parent {
    display: flex;
    align-items: center;   /* 垂直置中 */
    justify-content: center; /* 水平置中 */
    height: 200px;
}

Grid(IE10+ 部分支援)

.parent {
    display: grid;
    place-items: center;   /* 同時垂直水平置中 */
    height: 200px;
}

Absolute + Transform(IE9+)

.parent { position: relative; height: 200px; }
.child {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
}

Table-cell(IE8+)

.parent {
    display: table-cell;
    vertical-align: middle;
    height: 200px;
}

適用場景選擇指南

場景推薦方案IE 支援
單行文字(導航、按鈕)line-height = height全版本
多行文字/區塊(現代專案)FlexboxIE10+
需支援 IE9Absolute + TransformIE9+
需支援 IE8Table-cellIE8+
未知高度容器Flexbox / GridIE10+

小結

line-height = height 是單行文字垂直置中最簡潔、相容性最好的方案。多行或區塊置中請改用 Flexbox(首選)、Grid 或 Absolute+Transform,根據專案瀏覽器支援需求選擇。

copyright © 萬盛學電腦網 all rights reserved