| 場景 | 推薦方案 | 關鍵代碼 |
|---|---|---|
| 單行文字、固定高度容器 | Line-height 大法 | height: 50px; line-height: 50px; text-align: center; |
| 多行文字/未知尺寸、現代瀏覽器 | Flexbox 置中 | display: flex; justify-content: center; align-items: center; |
| 多行文字/未知尺寸、需支援 IE9+ | Absolute + Transform | position: absolute; top:50%; left:50%; transform: translate(-50%, -50%); |
| 表格儲存格 | Vertical-align | display: table-cell; vertical-align: middle; text-align: center; |
| Grid 佈局區域 | Grid 置中 | display: grid; place-items: center; |
.single-line-center {
height: 50px;
line-height: 50px; /* 必須等於固定高度 */
text-align: center; /* 水平置中 */
white-space: nowrap; /* 防換行破壞 */
overflow: hidden;
text-overflow: ellipsis; /* 內容過長截斷 */
}
⚠️ 多行文字會失效(行高疊加),僅限單行、不換行場景。
.flex-center {
display: flex;
justify-content: center; /* 主軸(水平)置中 */
align-items: center; /* 交叉軸(垂直)置中 */
min-height: 100vh; /* 全螢幕示例 */
text-align: center; /* 多行文字內部水平置中 */
}
-ms-flexbox 前綴,Autoprefixer 自動處理。.absolute-center {
position: relative; /* 父容器建立定位基準 */
min-height: 200px;
}
.absolute-center .content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center; /* 內部文字水平置中 */
max-width: 90%; /* 防止超出容器 */
}
.grid-center {
display: grid;
place-items: center; /* 一行搞定雙向置中 */
min-height: 100vh;
}
原文:<div style="line-height:50px;height:50px; padding:10px;" align="center">
問題:align="center" 為 HTML4 廢棄屬性、padding 會增加實際高度導致垂直偏移。
/* 改良版:純 CSS、語義化、無副作用 */
.center-box {
display: flex;
justify-content: center;
align-items: center;
height: 50px;
padding: 0 10px; /* 水平內距,不影響垂直置中 */
background: #f5f5f5;
border-radius: 4px;
}
/* 內容自動雙向置中,支援多行自動換行 */
.center-box span { text-align: center; }
原文提到「暫時想不到自適應高度解決方案」,現代答案就是 Flex/Grid:容器給 min-height,內容高度變化時自動保持置中,零 JS、零計算。
DIV 文字絕對置中:單行用 line-height、多行/未知尺寸用 Flex/Grid、相容 IE9 用 Absolute+Transform。建立統一工具類(.flex-center、.grid-center、.absolute-center),專案全域複用。拋棄 align="center"、padding 干擾高度、固定尺寸負邊距等歷史包袱,擁抱現代佈局原生置中能力。