首页 > Web开发 > 详细

html的五个居中的方法

时间:2019-10-26 11:28:09      阅读:112      评论:0      收藏:0      [点我收藏+]

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>

html的五个居中的方法

原文:https://www.cnblogs.com/2507148161----com/p/11742006.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!