如何让子元素在父元素中水平垂直居中七种方法?

YannZoe 2019-07-01

html:

<div class="container">
        <div class="box">green</div>
    </div>

第一种:定位+margin:auto

.container {
        position: relative;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        width: 100px;
        height: 100px;
        background: red;
    }

注意:兼容性较好,缺点:不支持IE7以下的浏览器
第二种:定位+margin-left+margin-top

.container {
        position: relative;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -50px;
        margin-top: -50px;
        width: 100px;
        height: 100px;
        background: red;
    }

注意:兼容性好;缺点:必须知道元素的宽高
第三种:定位+transfrom

.container {
        position: relative;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
        width: 100px;
        height: 100px;
        background: red;
    }

注意:这是css3里的样式;缺点:兼容性不好,只支持IE9+的浏览器
第四种:弹性盒子

.container {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        width: 100px;
        height: 100px;
        background: red;
    }

移动端首选
第五种:flex+margin: auto

.container {
        display: flex;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        margin: auto;
        width: 100px;
        height: 100px;
        background: red;
    }

移动端首选
第六种:形成table-cell,子元素设置display:inline-block

.container {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: red;
    }

注意:兼容性:由于display:table-cell的原因,IE67不兼容
第七种:line-height+display:inline

.container {
        width: 300px;
        height: 300px;
        line-height: 300px;
        text-align: center;
        background: yellow;
    }
    .box {
        display: inline;
        background: red;
    }

职场小白south Joe,望各位大神批评指正,祝大家学习愉快!

相关推荐