CSS 居中對(duì)齊
flex 居中
優(yōu)點(diǎn):可對(duì)未知高度進(jìn)行居中處理
<style> .wrap{height: 100%;display: flex; justify-content: center; align-items: center;align-content:center;} .other{background-color: #ccc; width: 400px;height: 400px;} /* 額外的樣式 可去除 */</style><div class="wrap"> <div class="other"> <h2>這是第二層的內(nèi)容 不會(huì)居中</h2> </div></div>position + translate 居中
優(yōu)點(diǎn): 可對(duì)未知高度進(jìn)行居中處理、嵌套層最少
<style> /* position 可選 absolute|fixed*/ .center{position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);} .other{background-color: #ccc; } /* 額外的樣式 可去除 */</style><div class="center other"> <h2>這一層的內(nèi)容 不會(huì)居中</h2></div>table-cell 居中
缺點(diǎn):1. 居中層需要設(shè)置寬度(.center)。 2.外層多嵌套一層(.cell) 3. 居中層必須設(shè)置寬度(允許 %)
<style> .wrap{display: table;width: 100%;height: 100%;} .cell{display: table-cell;vertical-align:middle;} .center{width: 400px;margin-left:auto;margin-right:auto;} .other{background-color: #ccc; height: 400px;} /* 額外的樣式 可去除 */</style><div class="wrap"> <div class="cell"> <div class="center other"> <h2>這一層的內(nèi)容 不會(huì)居中</h2> </div> </div></div>傳統(tǒng)居中 (2種)
缺點(diǎn):1. margin 值必須為auto。 2. 居中層必須設(shè)置高寬(允許 %) 3. 必須使用 position
<style> /* 1. left、top、right、bottom 可以任意,但必須相等 2. position 可選 absolute|fixed */ .center{position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;margin: auto;width: 400px;height: 400px;} .other{background-color: #ccc; } /* 額外的樣式 可去除 */</style><div class="center other"> <h2>這一層的內(nèi)容 不會(huì)居中</h2></div>缺點(diǎn): 居中層必須設(shè)置固定高寬,并且magin需要通過高寬計(jì)算得出。
<style> .wrap{position: relative;height: 100%;} .center{position: absolute;left: 50%;top: 50%; width: 400px;height: 300px; margin-left: -200px;margin-top: -150px;} .other{background-color: #ccc; } /* 額外的樣式 可去除 */</style><div class="wrap"> <div class="center other"> <h2>這一層的內(nèi)容 不會(huì)居中</h2> </div></div>總結(jié)
以上所述是小編給大家介紹的CSS 垂直水平居中的5種最佳解決方案,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VeVb武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選