「如何讓元素居中?」看似簡單,實則包含水平/垂直、固定/不定寬高、行內/塊級、單行/多行文本等多維變量。本文系統梳理 5 大核心方法,建立完整居中知識體系。
| 元素類型 | 方法 | 作用對象 | 核心條件 |
|---|---|---|---|
| 行內/行內塊/文本 | text-align: center |
父元素 | 子元素未浮動、未絕對定位 |
| 塊級元素 (定寬) | margin: 0 auto / margin-left: auto; margin-right: auto |
子元素自身 | 子元素有明確 width、未浮動 |
| Flex 容器 | justify-content: center |
父元素 | 現代首選,不限子元素類型 |
| Grid 容器 | place-items: center 或 justify-content: center |
父元素 | 兩維佈局首選 |
避坑:浮動元素、絕對定位元素脫離文檔流,
text-align和margin:auto皆失效。需先清除浮動或改用 Flex/Grid/定位方案。
.parent {
height: 100px;
line-height: 100px; /* 等於 height */
}
/* 子元素需為行內/行內塊,且無換行 */
.child { display: inline-block; vertical-align: middle; line-height: normal; } /* 重置行高防止多行錯亂 */
局限:僅適用於單行文本/單張圖片。多行文本、塊級元素無效。
適用於任意類型、任意尺寸元素的水平垂直居中,幾乎無副作用。
.parent {
position: relative; /* 建立定位上下文,防止子元素定位到 body */
width: 300px; height: 200px; /* 父元素需有尺寸 */
}
.child {
position: absolute;
top: 50%; left: 50%; /* 左上角對齊中心點 */
transform: translate(-50%, -50%); /* 向回偏移自身高寬一半 */
/* 無需知道子元素寬高! */
}

.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
/* 或簡寫:place-items: center; */
}
.parent {
display: grid;
place-items: center; /* 同時水平垂直居中 */
/* 或 place-content: center; 針對軌道對齊 */
}
vertical-align: middle + text-align: center.modal-overlay {
position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0,0,0,0.5);
display: flex; /* Flex 居中 */
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 24px;
border-radius: 8px;
max-width: 90vw; max-height: 90vh;
overflow: auto;
}