html的五个居中的方法

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>

猜你喜欢

转载自www.cnblogs.com/2507148161----com/p/11742006.html