CSS实现水平垂直居中实例
- PC端有兼容性要求,宽高固定,推荐absolute + 负margin
- PC端有兼容要求,宽高不固定,推荐css-table
- PC端无兼容性要求,推荐flex //移动端推荐使用flex
css
.boxs{ padding: 10px; background-color: #ccc; }
.wp{border:1px solid red;width:300px;height:300px;}
.box{background: green;}
.demo_01{position:relative;}
.demo_01 .box{position:absolute; background: green;top:50%;left:50%;margin-left:-50px;margin-top:-50px;}
.demo_01 .box.size{width:100px;height:100px;}
.demo_02{display:table-cell;text-align:center;vertical-align:middle;}
.demo_02 .box{display: inline-block;}
.demo_03{display:flex;justify-content:center;align-items:center;}
一. PC端有兼容性要求,宽高固定,推荐absolute + 负margin
<div class="wp demo_01">
<div class="box size">盒子水平垂直居中</div>
</div>
二, PC端有兼容要求,宽高不固定,推荐css-table
<div class="wp demo_02">
<div class="box">盒子水平垂直居中</div>
</div>
三, PC端无兼容性要求,推荐flex,
移动端推荐使用flex
<div class="wp demo_03">
<div class="box">盒子水平垂直居中</div>
</div>