第一种方式:position + margin(设置负的宽高一半)

优缺点:兼容性好,但是必须要知道父元素的宽高

div.box{
    weight:200px;
    height:400px;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-100px;
    margin-top:-200px;
}

第二种方式:position + transform(es6)

优缺点:兼容性不好,只支持ie9以上的。不需要知道父元素的宽高

div.box{
    weight:200px;
    height:400px;
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
}

第三种方式:纯定位 + margin auto

优缺点:兼容性很好,不支持ie7以下的。不需要知道父元素的宽高

div.box{
  width:200px;
  height:400px;
  position:absolute;
  left:0;
  right:0;
  top:0;
  bottom:0;
  margin:auto;
}

第四种方式:flex布局

优缺点:不是给子元素设置 是给容器父元素设置

<style>
    .box1 {
        height: 300px;
        width: 300px;
        border: 10px solid pink;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .box2 {
        height: 100px;
        width: 100px;
        background-color: #bfa;
    }
</style>
<div class="box1">
    <div class="box2"></div>
</div>

第五种方式:tabel布局

<style>
    .box1 {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    .box2 {
        display: inline-block;
    }
</style>
<div class="box1">
    <div class="box2"></div>
</div>

第六种方式:grid布局

<style>
    .box1 {
        display: grid;
        width: 500px;
        height: 500px;
    }
    .box2 {
        justify-self: center;
        align-self: center;
    }
</style>
<div class="box1">
    <div class="box2"></div>
</div>

第七种方式:display:inline-block + vertical-align:middle


小情绪
1 声望0 粉丝