水平垂直居中
1.知道自身的宽高
<style>
.wrapper{
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
.child{
width: 100px;
height: 100px;
border: 1px solid black;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;//-自身宽度的一半
margin-top: -50px;//-自身高度的一半
}
</style>
<div class="wrapper">
<div class="child"></div>
</div>
2.不知道自身的宽高
(1)给自身设置
.child{
width: 100px;
height: 100px;
border: 1px solid black;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;//吸收剩余空间
}
//宽(高)为auto的绝对定位元素,
//可以通过left、right、top、bottom设置它的宽高
(2)给自身设置
.child{
width: 100px;
height: 100px;
border: 1px solid black;
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
(3)给父级设置弹性盒
.wrapper{
display:flex;
justify-content:center;
align-items:center;//解决多行居中
}
效果
水平居中
1.给自身设置
.child{
margin:0 auto;
}
2.给父级设置弹性盒(参考上面)