<div class="parent"> <div class="son">123</div> </div>
一、使用css3的transform
.parent{ width: 200px; height: 200px; background-color: red; position: relative; } .son{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
二、flex布局
.parent{ width: 200px; height: 200px; background-color: red; display: flex; justify-content: center; align-items: center; }
三、使用css方法
.parent{ width: 200px; height: 200px; background-color: red; display:table-cell; text-align: center; vertical-align: middle; } .son{ display: inline-block; vertical-align: middle; }
四、兼容最佳(IE7以上都可以)
.parent{ width: 200px; height: 200px; background-color: red; position: relative; } .son{ width: 20px; height: 20px; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
原文:https://www.cnblogs.com/qingmodaytoy/p/12003552.html