纯CSS实现水平垂直居中最近的几场面试都问了这个问题,自己也只答了2种,感觉面试官不满意,特地总结了几种在开发中比较实用的方法,与大家分享。一、需要知道width,height的方案1.绝对定位 + 负外边距<style type=“text/css”> .warp{ position: relative; } .box { width: 200px; height: 100px; position: absolute; top: 50%; left: 50%; padding: 0; margin-left: -100px; /* (width + padding)/2 / margin-top: -50px; / (height + padding)/2 */ }</style><div class=“warp”> <div class=“box”> </div></div>因为margin/padding的百分比值是参照父元素的width,所以无法用百分比。二、不需要知道width,height方案1.绝对定位 + margin:auto<style type=“text/css”> .warp{ position: relative; } .box { width: 200px; height: 100px; position: absolute; padding: 0; margin: auto; left: 0; right: 0; top: 0; bottom: 0; }</style><div class=“warp”> <div class=“box”> </div></div>利用margin:auto自动计算实现2.绝对定位 + transform<style type=“text/css”> .warp{ position: relative; } .box { width: 200px; height: 100px; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }</style><div class=“warp”> <div class=“box”> </div></div>利用translate的百分比是相对本元素宽/高这一特点实现3.flex<style type=“text/css”> .warp{ display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: -webkit-box; display: flex; -webkit-box-align: center; -moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; -webkit-box-pack: center; -moz-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; } .box { width: 200px; height: 100px; }</style><div class=“warp”> <div class=“box”> </div></div>其他除此之外还有table-cell布局,inline-block布局等,由于在项目中很少用到,而且感觉table布局坑太多,就不做描述,有兴趣请自行查找。本文如有错误,请在评论区提出。最后,四月求个offer~~谢谢