「水平置中」容易(text-align: center / margin: 0 auto),「垂直置中」才是歷代前端工程師的痛點。根因在於 CSS 視覺格式化模型:區塊級元素預設填滿寬度、高度由內容撐開,垂直方向無「自動置中」機制。
.center-flex {
display: flex;
justify-content: center; /* 水平 */
align-items: center; /* 垂直 */
min-height: 100vh; /* 全螢幕高度示例 */
}
gap、flex-wrap)。.center-grid {
display: grid;
place-items: center; /* 等同 align-items + justify-items */
min-height: 100vh;
}
.center-absolute {
position: relative; /* 父容器建立定位基準 */
min-height: 100vh;
}
.center-absolute .box {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%); /* 位移自身 50% 寬高 */
/* 寬高可不指定,由內容撐開 */
}
.center-margin {
position: relative;
}
.center-margin .box {
position: absolute;
top: 50%; left: 50%;
width: 300px; height: 200px; /* 必須固定尺寸 */
margin-top: -100px; /* -height/2 */
margin-left: -150px; /* -width/2 */
}
IE8+ 相容,但需預知尺寸,響應式維護麻煩,現代專案少用。
.single-line {
height: 50px;
line-height: 50px; /* 等於固定高度 */
text-align: center; /* 水平置中 */
}
僅適用於單行、不換行文字,最輕量、相容性最好(IE6+)。
td, th { vertical-align: middle; }
表格儲存格天生支援垂直置中,無需額外包裹層。
position: relative 導致絕對定位相對 body 定位。min-height),垂直置中無視覺效果。transform 會改變 position: fixed 子元素的定位基準(相對最近的 transform 祖先而非 viewport)。line-height 置中會失效,改用 Flex/Grid。置中不再是難題,關鍵在於選對工具。新專案預設用 display: flex; place-items: center(或 place-content: center),舊專案維護用 transform: translate(-50%, -50%),單行文字用 line-height。建立統一團隊規範,置中問題一勞永逸。