.centered {
position: absolute;
left: 50%;
top: 50%;
width: 740px;
height: 400px;
margin-left: -370px; /* 寬度一半 */
margin-top: -200px; /* 高度一半 */
}
left: 50%:元素左邊緣對齊容器水平中心線。margin-left: -370px:將元素向左拉回自寬一半,使元素中心線與容器中心線重合。top: 50% + margin-top: -height/2。關鍵認知:left/top 定位的是元素邊緣,margin 位移的是元素整體。
position: relative/absolute/fixed(建立定位上下文)。transform 技巧)。.parent {
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
min-height: 100vh; /* 視窗高度 */
}
.parent {
display: grid;
place-items: center; /* 同時水平垂直置中 */
min-height: 100vh;
}
.centered {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* 相對自身尺寸位移 50% */
}
translate 百分比基準是自身尺寸。transform-style: preserve-3d 緩解。| 方法 | 需知寬高 | 瀏覽器支援 | 適用場景 |
|---|---|---|---|
| margin 負值 | 是 | IE6+ | 舊專案維護、固定尺寸彈窗 |
| transform | 否 | IE10+ | 動態尺寸、RWD、彈窗、Tooltip |
| Flexbox | 否 | IE10+ (部分) | 容器置中、單欄/多欄佈局 |
| Grid | 否 | IE10+ (前綴) | 二維佈局、整頁置中 |
transform 方案(搭配 Polyfill)。fixed 定位元素上使用 margin: auto 置中(行為不一致)。display: flow-root。掌握置中原理,不再靠試誤調整像素值。更多 CSS 佈局核心技巧,請持續關注本站系列文章。