在 Flexbox/Grid 普及前,position: absolute + margin 負值 是全螢幕置中唯一可靠方案。雖現代佈局已有更優選擇,但理解此經典模式對維護舊專案、處理特殊定位場景(如 Modal、Toast、Loading 遮罩)仍有價值。
<style>
/* 容器:相對定位建立參考系,或 body 直接作為參考 */
.viewport {
position: relative; /* 或 fixed 全螢幕 */
width: 100vw;
height: 100vh;
}
/* 置中元素:已知寬高 */
.centered {
position: absolute;
top: 50%;
left: 50%;
width: 300px; /* 必須已知寬度 */
height: 200px; /* 必須已知高度 */
margin-top: -100px; /* 負的 1/2 高度 */
margin-left: -150px; /* 負的 1/2 寬度 */
background: #fff;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}
</style>
<div class="viewport">
<div class="centered">完全置中的內容區塊</div>
</div>
top:50%; left:50% 將元素左上角移至容器中心點margin-top: -height/2; margin-left: -width/2 將元素中心點拉回容器中心若寬高不固定(如 Modal 內容隨內容撐開),負邊距法失效。現代方案:
.centered-auto {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 不需知道寬高 */
/* 內容自適應撐開 */
max-width: 90%;
max-height: 90%;
overflow: auto;
}
.viewport-flex {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh; /* 全螢幕最小高度 */
}
.centered-flex { /* 無需定位、負邊距、transform */ }
.viewport-grid {
display: grid;
place-items: center;
min-height: 100vh;
}
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 固定尺寸彈窗、Loading、Tooltip | 負邊距 / Transform | 脫離文檔流、疊加層級控制精確 |
| 動態尺寸 Modal、對話框 | Transform / Flex | 不需預知尺寸、響應式友善 |
| 全頁面佈局、Hero Section | Flex / Grid | 語意清晰、支援多子元素佈局 |
| IE8- 相容專案 | 負邊距 + 表格佈局 Hack | 唯一可行方案 |
max-width: 90vw; max-height: 90vh; overflow: auto; 確保內容可滾動。transform/filter/perspective;或改用 Flex/Grid 避免 transform。opacity<1、transform、filter、z-index 非 auto)。總結:經典「絕對定位 + 負邊距」適用於固定尺寸、需脫離文檔流的置中場景。現代開發首選 Flexbox/Grid,動態尺寸用 Transform。理解經典模式原理,有助於除錯與跨時代代碼維護。