1:給box添加一個偽元素,通過text-align:center;和vertical-align:middle;兩條屬性讓其居中
<style>
.box{width:500px;height:500px;border:1px solid #000;text-align:center;}
.box:after{content:"";display:inline-block;height:100%;vertical-align:middle;}
.zi{width:100px;height:100px;background:#0f0;display:inline-block;vertical-align:middle;}
</style>
<div class="box"><div class="zi"></div><!-- :after --></div>
2:通過定位,給子元素書寫4個方向的值都為0和margin:0 auto;讓其居中
<style>
.box{width:500px;height:500px;border:1px solid #000;position:relative;}
.zi{width:100px;height:100px;background:#0f0;
position:absolute;
left:0;right:0;top:0;bottom:0;margin:auto;
}
</style>
<div class="box"><div class="zi"></div></div>
3:也是通過定位,讓子元素的左上的點定位在中心,然后通過margin來調整,不過這種方法是需要你根據子元素的大小來手動調整margin的距離的
<style>
.box{width:500px;height:500px;border:1px solid #000;position:relative;}
.zi{width:100px;height:100px;background:#0f0;
position:absolute;
left:50%;top:50%;margin:-50px 0 0 -50px;
}
</style>
<div class="box"><div class="zi"></div></div>
4:這個於第三個幾乎一樣,但他是通過translate來調整,好處就是不用手動調整距離了,但存在兼容問題
<style>
.box{width:500px;height:500px;border:1px solid #000;position:relative;}
.zi{width:100px;height:100px;background:#0f0;
position:absolute;
left:50%;top:50%;transform:translate(-50%,-50%);
}
</style>
<div class="box"><div class="zi"></div></div>
5:這是通過彈性盒的兩條居中屬性來達成的,也是最方便的一種方法,但它也有兼容問題,只能在移動端上使用
<style>
.box{width:500px;height:500px;border:1px solid #000;
display:flex;justify-content:center;align-items:center;
}
.zi{width:100px;height:100px;background:#0f0;}
</style>
<div class="box"><div class="zi"></div></div>