很多界面需要用到元素水平垂直居中的布局方式。记录一下几种常用的方法
- 定位法
<style> body,html{ background-color: #ccc; } .box{ width: 300px; height: 300px; border: 1px solid red; margin: 100px auto; position: relative; } .inbox{ width: 100px; height: 100px; border: 1px solid blue; position: absolute; left: calc(50% - 50px); top: calc(50% - 50px); } </style> <div class="box"> <div class="inbox"></div> </div>
- 定位结合Css3 (此方法在定位基础上优化了, 子元素宽高未知,也可以居中)
<style> body,html{ background-color: #ccc; } .box{ width: 300px; height: 300px; border: 1px solid red; margin: 100px auto; position: relative; } .inbox{ width: 100px; height: 100px; border: 1px solid blue; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } </style> <div class="box"> <div class="inbox"></div> </div>
- 空标签法 (不建议使用,但是可以知道有这么个方法存在,适合面试装杯)
<style>
.box{ width: 300px; height: 300px; border: 1px solid red; margin: 100px auto; text-align: center; } .inbox{ display: inline-block; } .empty{ display: inline-block; width: 0; height: 100%; vertical-align: middle; } </style> <div class="box"> <span class="empty"></span> <div class="inbox">水平垂直居中</div> </div>
- table格子法 (同上)
<style> body,html{ background-color: #ccc; } .box{ width: 300px; height: 300px; border: 1px solid red; display: table-cell; vertical-align: middle; } .inbox{ text-align: center; } </style> <div class="box"> <div class="inbox">水平垂直居中</div> </div>
- 弹性布局(最实用,最简单)
<style> body,html{ background-color: #ccc; } .box{ width: 300px; height: 300px; border: 1px solid red; margin: 100px auto; display: flex; justify-content: center; align-items: center; } </style> <div class="box"> <div class="inbox">水平垂直居中</div> </div>