学习笔记 - 垂直居中的几种方式

114 阅读1分钟

知道元素高度的情况下:
1.行高居中内容
.parent{
    height: 50px;
    line-height: 50px;
}
2.利用定位和margin居中
.child{
    position: relative; //position: absolute; position: fixed;
    height: 50px;
    top: 50%;
    margin-top: -25px;
}

不知道元素高度的情况: //同样适用知道高度的情况
1.css3的transform居中
.child{
    position top:50%;
    transform: translateY(-50%);
}
2.flex居中
body{
    display: flex;
    align-items: center; /定义body的元素垂直居中/
    justify-content: center; /定义body的里的元素水平居中/
}
3.黑科技手段实现垂直居中
<div class="container">
    <div class="dialog"></div>
</div>
.container {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0,0,0,.5);
    text-align: center;
    font-size: 0;
    white-space: nowrap;
    overflow: auto;
}

.container:after {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.dialog {
    display: inline-block;
    vertical-align: middle;
    text-align: left;
    font-size: 14px;
    white-space: normal;
}