让浮动的元素垂直居中

<div class="a">
    <div class="b">
        元素居中
    </div>
</div>

父元素设置相对定位

1.子元素若高度300px,设置绝对定位,top:50% margin-top:-150px(子元素高度的一半);

.a{
    width:800px;
    height:600px;
    position:relative;
    background:black;
}
.b{
    width: 500px;
    height: 300px;
    margin-top:-150px;
    position: absolute;

    top: 50%;
    background-color: white; 
    float:left;
}

 2.子元素高度未知:

设置绝对定位,上下左右均为0,margin:auto; 

.a{
    width:800px;
    height:600px;
    position:relative;
    background:black;
}
.b{
    width: 500px;
    height: 300px;

    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    background-color: white; 
    float:left;
}
原文地址:https://www.cnblogs.com/danranysy/p/4775976.html