3 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個(gè)贊
有兩種方法可以做到這一點(diǎn):
.lightbox {
margin: 0 auto;
}
這僅在父組件內(nèi)水平居中。如果這是您想要做的,這是一種非常簡單的方法。
如果沒有,試試這個(gè):
.lightbox {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
垂直和水平居中元素的流行方法是使用:
top: 50%;
left: 50%;
transform: translate( -50%, -50% );
您可以將其與絕對(duì)或固定定位一起使用。top并將left左上角移動(dòng)到屏幕中心,同時(shí)translate( -50%, -50% )將元素移回左側(cè)和元素寬度/高度的頂部 50%,將元素的中心放在頁面的中心。
.box {
position: fixed;
top: 50%;
left: 50%;
transform: translate( -50%, -50% );
/* For Demo */
width: 75vw;
height: 75vh;
background-color: #ccc;
}
<div class="box"></div>

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
使用彈性盒:
main {
background-color: teal;
}
.modal-container {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: gray;
}
.modal {
display: block;
max-width: 300px;
width: 90%;
max-height: 300px;
height: 90%;
background-color: white;
}
<main>
<div class="modal-container">
<div class="modal">
<h2>yes</h2>
</div>
</div>
</main>
添加回答
舉報(bào)