移动端css水平垂直居中

水平垂直居中

1.margin 负值调整偏移实现

兼容性: 当前流行的使用方法。

    <div class="box">
        <div class="content"></div>
    </div>
.box{
    width: 100%;
    height: 100%;
}
.content{
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left:-50px;
    margin-top:-50px;
   /* transform: translate(-50%,-50%);*/

    height:100px;/* height的一半 */
    width:100px; /*width的一半 */
    background: pink;
}

首先设置绝对定位元素,相对于原点left,top设置50%。由于是基于content元素的开始位置,真正居中,需要设置content的中心点 水平垂直居中。

2.margin auto 实现

兼容性:IE7及之前版本不支持

    <div class="box">
        <div class="content"></div>
    </div>
/* margin:auto */
.box{
    position: relative;/* 非static定位 */

    width: 200px;
    height: 200px;
    border: 1px solid;
}
.content{
    position:absolute;/* 相对于父元素第一个非static定位 */
    margin:auto;
    top:0;
    left:0;
    right: 0;
    bottom: 0;

    height:100px;
    width:100px; 
    background: pink;
}

要点:绝对定位,margin:auto, TRBL 。

 2.flex 实现

兼容性:css3特性

    <div class="box">
        <div class="content"></div>
    </div>
.box{
    display: flex;
    justify-content: center;
    align-items: center;

    width: 200px;
    height: 200px;
    border: 1px solid;
}
.content {
    width: 100px;
    height: 100px;
    background: pink;
}

设置容器使用flex布局,justify-content 设置主轴居中(水平居中),align-items 设置垂直居中。

 4)table-cell 实现

    <div class="box">
        <div class="content"></div>
    </div>
.box{
    display: table-cell;
    text-align: center;
    vertical-align: middle;

    width: 200px;
    height: 200px;
    border: 1px solid;
}
.content{

    display: inline-block;
    height:100px;
    width:100px; 
    background: pink;
}

table-cell 布局,把内容水平居中和垂直居中。

原文地址:https://www.cnblogs.com/bg57/p/8661563.html