第一种:将元素通过display:inline-block转化为行内块元素居中,例如:

.box{width:500px;height:500px;box-shadow:0 0 5px #000;text-align:center;font-size:0;}

.box .zi{width:120px;height:100px;background:#0f0;display:inline-block;vertical-align:middle;}

.box:after{content:"";display:inline-block;height:100%;vertical-align:middle;}

第二种:用定位的方式将之移动到位置,例如:

.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}

.box .zi{width:120px;height:100px;background:#0f0;

position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}

第三种:类似第二中只不过通过百分比调整位置,例如

.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}

.box .zi{width:120px;height:100px;background:#0f0;position:absolute;left:50%;top:50%;margin:-50px 0 0 -60px;}

第四种:类似第三种,但是在调整回到中心位置时使用transform:translate( ,)进行调整,例如

.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}

.box .zi{width:120px;height:100px;background:#0f0;

position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);}

第五种:使用弹性盒(display:flex),例如

.box{width:500px;height:500px;box-shadow:0 0 5px #000;display:flex;justify-content:center;align-items:center;}

.box .zi{width:120px;height:100px;background:#0f0;}

以上最常用的五种方式,除此之外还有很多方式,根据每个人的习惯不同个人用法不同,如有疑问请谅解。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐