今天去面試的時(shí)候,被問到css怎么實(shí)現(xiàn)高度不定的垂直居中,突然就懵了,之前面試的都是js相關(guān)知識,發(fā)現(xiàn)css的知識自己缺少總結(jié),今天就先理一下不定高的垂直居中吧!
首先第一種:用flex布局實(shí)現(xiàn)不定高垂直居中:
html代碼:一個(gè)父div,一個(gè)子div;
<div class="p">
<div class="s">
我是不定高div,需要垂直居中
我是不定高div,需要垂直居中
</div>
</div>
css代碼:父div固定高度,子div根據(jù)內(nèi)容自適應(yīng);
通過設(shè)置父div為flex,然后設(shè)置主抽和交叉軸方向center即可;
.p{
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto;
width: 600px;
height: 400px;
background-color: #1e88e5;
}
.s{
width: 300px;
background-color: #fd9927;
}
效果截圖:

缺點(diǎn):瀏覽器兼容性不好,IE10以上才能用;
第二種:position定位實(shí)現(xiàn)不定高垂直居中:
html代碼一樣,直接上css代碼:
.p{
position: relative;
margin: 0 auto;
width: 600px;
height: 400px;
background-color: #1e88e5;
}
.s{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 300px;
background-color: #fd9927;
}
注意父div一定要設(shè)置relative或者fixed,不然的話會(huì)一直找其祖先元素搜索設(shè)置了relative或者fixed的div,然后根據(jù)其定位,都沒有的話是根據(jù)body定位;
解釋一下為啥要設(shè)置transform, 因?yàn)樵O(shè)置top和left為50%是按照子div的左上定點(diǎn)實(shí)現(xiàn)定位的,這樣會(huì)導(dǎo)致子div自身的寬度和高度不在居中范圍內(nèi),設(shè)置transform之后,將其自身的寬度和高度向上、左移動(dòng)其自身的50%,就實(shí)現(xiàn)和水平和垂直居中;
效果圖就不上了,太占地,老鐵們可以自己敲一遍代碼查看效果;
缺點(diǎn):1、IE8不支持;2、transform屬性需要寫瀏覽器廠商前綴;3、可能干擾其他transform效果;4、某些情形下會(huì)出現(xiàn)文本或元素邊界渲染模糊的現(xiàn)象;
目前知道這兩種,還有table和table-cell布局實(shí)現(xiàn)垂直居中后,會(huì)導(dǎo)致子元素繼承父元素的高度,不明白為啥,先不寫了;
老鐵們有好的方法可以留言。