实现元素水平居中和垂直居中的几种方法

情景:父盒子.wrap,子元素.child,实现子元素在父元素中水平和垂直居中

*{
    padding: 0;
    margin: 0;
}
body,html{
    width: 100%;
    height: 100%;
    background-color: #eee;
    overflow: hidden;
}
.wrap{
    width: 90%;
    margin: 100px auto;
    background-color: #fff;
    height: 400px;  
}
.wrap .child{
    width: 200px;
    height: 200px;
    background-color: red;
}
基本样式
<body>
    <div class="wrap">
        <div class="child"></div>
    </div>
</body>

方式一:父元素相对定位,子元素绝对定位,margin:auto

.wrap{
    position: relative;
}
.child{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

方式二:父元素相对定位,子元素绝对定位,margin负一半自身宽高

.wrap{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

方式三:父元素相对定位,子元素绝对定位,css3位移自身负一半宽高

.wrap{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

方式四:给父盒子使用弹性布局flex

.wrap{
    display: flex;
    justify-content: center; //主轴
    align-items: center;  //附轴
}

 方式五:弹性布局,旧的写法

.wrap{
    display: -webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;
}

猜你喜欢

转载自www.cnblogs.com/xiaoyue-/p/10650128.html