CSS元素垂直居中一直都是一個讓人頭疼的問題憔恳,這里總結(jié)了4種方法,當(dāng)然通過改變定位可以有6種甚至更多败砂。
1.position配合margin
這個基本可以說是爛大街的方法了们妥,好處就是兼容性好,直接上代碼郎笆。
.content{
position:absolute;
width:550px;
height:364px;
top:50%;
left:50%;
margin-left:-275px;
margin-top:-182px;
background:url("images/love.jpg");
}
2.position配合margin改進(jìn)
IE6-9不兼容谭梗,使用CSS3函數(shù)calc()
.content{
position:absolute;
top: calc(50% -182px);? ? //?top移動的距離其實(shí)就是(總高度-容器高度)/2,有沒有覺得這個思路很酷宛蚓?
left: calc(50% -275px);??
width:550px;
height:364px;
background:url("images/love.jpg");
}
3.position配合transform(對于不定寬高容器同樣適用)
同樣還是不支持IE6-IE9激捏,因?yàn)閠ransform為CSS3新屬性。
.content{
position:absolute;
top:50%;
left:50%;
width:550px;
height:364px;? ?
transform:translate(-50%,-50%);
background:url("images/love.jpg");
}
4.flex配合margin? (對于不定寬高容器同樣適用)
同樣還是不支持IE6-IE9凄吏,因?yàn)?b>flex為CSS3新屬性远舅。
body{? ?//父元素
display:flex;
height:500px;
}
.content{? //子元素
margin:auto;
background:url("images/love.jpg");
}