CSS中階
CSS 水平垂直置中的方法
方法一:Flexbox(最推薦)
.parent {
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
}
簡潔直覺,適用於大多數場景,是現代開發的首選。
方法二:CSS Grid
.parent {
display: grid;
place-items: center; /* 等同 justify-items + align-items */
}
place-items: center 是最精簡的寫法,適合同時需要 Grid 布局的場景。
方法三:position + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
不需知道子元素的尺寸,適合彈出視窗(Modal)或覆蓋層。
方法四:margin: auto(僅水平)
.child {
width: 200px;
margin: 0 auto; /* 僅水平置中,垂直無效 */
}
只能水平置中,且子元素需設定寬度。
方法比較
| 方法 | 水平 | 垂直 | 需知尺寸 | 推薦程度 |
|---|---|---|---|---|
| Flexbox | ✅ | ✅ | ❌ | ⭐⭐⭐ |
| Grid | ✅ | ✅ | ❌ | ⭐⭐⭐ |
| position + transform | ✅ | ✅ | ❌ | ⭐⭐ |
| margin: auto | ✅ | ❌ | ✅ | ⭐ |
✦ AI 模擬面試
輸入你的答案,AI 即時分析精準度與改進空間
登入後即可使用 AI 評分
