實現文字在 div 中水平垂直雙向居中,不再需要複雜的表格佈局。掌握 text-align 與 line-height 黄金組合,輕鬆搞定單行文字居中。
.absolute-center {
height: 50px; /* 固定高度 */
line-height: 50px; /* 行高 = 高度 → 垂直居中 */
text-align: center; /* 水平居中 */
/* 可選:防止文字溢出 */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
<div class="absolute-center">完美居中的文字內容</div>
| 屬性 | 作用機制 | 適用範圍 |
|---|---|---|
text-align: center |
控制行內/行內塊級元素水平對齊 | 所有瀏覽器,所有行內內容 |
line-height = height |
行框高度等於容器高度,文字在行框中垂直居中 | 單行文字、單行行內元素 |
多行文字會導致行高疊加,破壞垂直居中。多行居中請用:
.flex-center {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
}
.grid-center {
display: grid;
place-items: center; /* 等同 align-items + justify-items */
height: 200px;
}
.absolute-center {
position: relative;
height: 200px;
}
.absolute-center > span {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.table-center {
display: table;
height: 200px;
width: 100%;
}
.table-center > span {
display: table-cell;
vertical-align: middle;
text-align: center;
}
line-height = height 最簡潔高效align-items: center