内容高度不固定的元素——垂直居中

html,body{
    margin: 0;
    height: 100%;
}

.box{
    background: #ccc;
    position: fixed;
    width: 100%;
    height: 100%;
    text-align: center;
    top:0px;
    left:0px;
}

.content{
    display: inline-block;
    vertical-align: middle;
    width: 300px;
    height: 300px;
    background: skyblue;
}

.box::before{
    display: inline-block;
    height: 100%;
    content: '';
    vertical-align: middle;
    width:1px;
    background:blue;
}

对应的html

<div class="box">
    <div class="content"></div>
</div>

原理:

父元素box覆盖整个页面,box的伪类before是其子元素,该子元素高度为100%,将父元素撑开,box的子元素before和content都是inline-block,且vertical-align: middle;,两个子元素居中对齐;

效果:

方法二:直接用函数:

@mixin dialogCon1($w, $color, $radius) {
    width: $w;
    height: auto;
    background-color: $color;
    border-radius: $radius;
    position: fixed;
    top: 50%;
    left: 50%;
    /*-webkit-transform: translateZ(0) scale(1.0, 1.0);*/
    -webkit-transform: translate(-50%, -50%) scale(1.0, 1.0);
    -ms-transform: translate(-50%, -50%) scale(1.0, 1.0);
    transform: translate(-50%, -50%) scale(1.0, 1.0);
    -webkit-font-smoothing: subpixel-antialiased;
}

缺点是IE9不支持transform,所以弹窗推荐用方法 一

原文地址:https://www.cnblogs.com/xiaozhumaopao/p/7098756.html