.centered {
position: absolute;
left: 50%; top: 50%;
width: 500px; height: 300px;
margin: -150px 0 0 -250px; /* 負一半自身高寬 */
background: #000;
}
優點:相容性極佳(IE8+);缺點:需知元素確切尺寸,內容超出會被截斷。
.parent {
position: relative;
float: left;
left: 50%; /* 父元素右移 50% */
}
.child {
position: relative;
float: left;
right: 50%; /* 子元素左移 50% */
}
原理:父元素左邊緣對齊視窗中心,子元素右邊緣對齊父元素中心,實現子元素中心點與視窗中心點重合。注意:代碼片段中 rightright:50% 為筆誤,應為 right: 50%。
| 場景 | 推薦方案 | 瀏覽器支援 |
|---|---|---|
| 單元素水平垂直置中 | Flexbox:display:flex; justify-content:center; align-items:center; | 全瀏覽器 |
| 不定尺寸彈性置中 | Grid:display:grid; place-items:center; | 全瀏覽器 |
| 舊專案相容 IE11 | Transform:top:50%; left:50%; transform:translate(-50%,-50%); | IE10+ |
| 文字/行內元素置中 | text-align:center + line-height 或 vertical-align:middle | 全瀏覽器 |
建議:新專案優先 Flexbox/Grid,僅在極舊環境維護時使用負邊距或 Transform 方案。