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改進
IE6-9不兼容,使用CSS3函數(shù)calc()
.content{
position:absolute;
top: calc(50% -182px);? ? //?top移動的距離其實就是(總高度-容器高度)/2,有沒有覺得這個思路很酷?
left: calc(50% -275px);??
width:550px;
height:364px;
background:url("images/love.jpg");
}
3.position配合transform(對于不定寬高容器同樣適用)
同樣還是不支持IE6-IE9,因為transform為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,因為flex為CSS3新屬性。
body{? ?//父元素
display:flex;
height:500px;
}
.content{? //子元素
margin:auto;
background:url("images/love.jpg");
}