方法一:使用flex
display: flex;
justify-content: center;
align-items: center;
该方法能水平垂直居中不定宽高的div
方法二:div绝对定位水平垂直居中【transform变形】
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
方法三:将父盒子设置为table-cell元素,可以使用text-algin:center和vertical-algin:middle实现水平、垂直居中。
display: table-cell;
text-align: center;
vertical-align: middle;
子元素需要设置display:inline-block;
方法四:对盒子用绝对定位,用calc计算位置
#app{
width: 200px;
height: 200px;
position: relative;
}
.in{
width: 50px;
height: 50px;
border: 1px solid red;
position: absolute;
left: calc((200px - 50px)/2);
top: calc((200px - 50px)/2);
方法五:div绝对定位,margin:auto实现绝对定位的居中
.in{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
方案六:div绝对定位,margin负间距水平垂直居中
width: 50px;
height: 50px; position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;