#centerdiv {
position: absolute;
top: 50%; left: 50%;
width: 300px; height: 200px;
margin: -100px 0 0 -150px; /* 高/寬的一半 */
background: black;
}
原理:先將左上角置於視窗中心,再用負外邊距向回拉半個寬高。缺點是必須知道元素固定尺寸。
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
無需知道子元素尺寸,支援動態內容,且相容 IE10+。
.container {
display: grid;
place-items: center;
min-height: 100vh;
}
.centered {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
適用於無法控制父容器樣式的場景(如第三方 Widget 嵌入)。