工作中遇到垂直居中问题,特此总结了一下几种方式与大家分享。
1、使用绝对定位垂直居中
.absolute_center{
/*display:none;*/
position:absolute;
width:200px;
height:200px;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
background:#518fca;
resize:both;/*用于设置了所有除overflow为visible的元素*/
overflow:auto;
}
2、负marginTop方式
已知元素高度后,使用绝对定位将top设置为50%,mergin-top设置为内容高度的一半(height + padding) / 2;内容超过元素高度时需要设置overflow决定滚动条的出现
原理:top:50%元素上边界位于包含框中点,设置负外边界使得元素垂直中心与包含框中心重合;
.negative_margin_top{
position:absolute;
top:50%;
left:0;
right:0;
margin:auto;
margin-top:-100px; /*-(height+padding)/2*/
width:200px;
height:200px;
}