元素的水平垂直居中解决方法
有时候为了使页面元素看起来更美观,常常会让元素水平居中,垂直居中。下面总结了几个常用的方法。 首先HTML结构如下: 1 <div class="out"> 2 <div class="in">布局</div> 3 </div> 方法1、使用最流行的flex布局方案。 1 .out { 2 display: flex; 3 justify-content: center; 4 align-items: center; 5 } 方法2、使用定位和偏移 1 .out { 2 position: relative; 3 } 4 .in { 5 position: absolute; 6 top: 50%; 7 left: 50%; 8 transform: translate(-50%, -50%); 9 } 使用transform可以不用考虑内部元素的宽高。 方法3、使用定位和负margin 1 .out { 2 position: relative; 3 } 4 .in { 5 position: absolute; 6 top: 50%; 7 left: 50%; 8 margin-left: -25px; 9 margin-top: -12.5px; 10 } 此时,需要明确内部元素的宽高。(这里设置的内部元素in是高25px,宽50px) 方法4、使用定位和margin