【css】常用的几种水平垂直居中方式与盒子模型,面试经常问到!
生活随笔
收集整理的這篇文章主要介紹了
【css】常用的几种水平垂直居中方式与盒子模型,面试经常问到!
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
div水平垂直居中
假設(shè)結(jié)構(gòu)為此,2個div嵌套
<div class="box"><div class="content"></div> </div>?
實(shí)現(xiàn)方式1:
absolute絕對定位+margin位移實(shí)現(xiàn)
這種方式適用于內(nèi)外2個div的寬高是已知時使用。外層使用相對定位,內(nèi)層使用絕對定位50%,并使用位移寬高的一半使之居中
.box{background-color: yellow;width: 300px;height: 300px;position: relative;border: 1px solid red; } .content{background-color: red;width: 100px;height: 100px;position: absolute;top: 50%;left: 50%;margin: -50px 0 0 -50px; }實(shí)現(xiàn)方式2:
transform實(shí)現(xiàn)
這種方式,幾乎和上一直一樣。但是如果子div寬高不定時,也可以實(shí)現(xiàn)居中。比第一種好點(diǎn)。
.box{background-color: yellow;width: 300px;height: 300px;position: relative;border: 1px solid red; } .content{background-color: red;position: absolute;width: 100px;height: 100px;top: 50%;left: 50%;transform: translate(-50%,-50%); }實(shí)現(xiàn)方式3:
flex布局實(shí)現(xiàn),使用justify-content和align-items實(shí)現(xiàn)
.box{background-color: yellow;width: 300px;height: 300px;display: flex;/*flex布局*/justify-content: center;/*水平居中*/align-items: center;/*垂直居中*/border: 1px solid red; } .content{background-color: red;width: 100px;height: 100px; }?
盒子模型
盒子模型由內(nèi)容、內(nèi)邊距、邊框、外邊距組成。
上方是一張圖,下方是盒子模型
<img src="https://www.runoob.com/try/demo_source/250x250px.gif" width="250" height="250"> <div class="ex">一個盒子</div> .ex{width: 220px;padding: 10px;border: 5px solid red;margin: 0; }這是盒子結(jié)構(gòu):
?
這是內(nèi)容:
這是內(nèi)邊距:
這是邊框:
外邊距為0:
?
轉(zhuǎn)載于:https://www.cnblogs.com/wuhairui/p/10944661.html
總結(jié)
以上是生活随笔為你收集整理的【css】常用的几种水平垂直居中方式与盒子模型,面试经常问到!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。