首先来两个元素
<div class="box">
<div class="son"></div>
</div>
给元素添加样式
.box{
height:400px;
width:400px;
background-color: #ccc;
margin: 100px auto;
}
.son{
width:200px;
height:200px;
background-color: red;
}
1.在知道元素的宽高情况下
.box{
height:400px;
width:400px;
background-color: #ccc;
margin: 100px auto;
position: relative;
}
.son{
width:200px;
height:200px;
background-color: red;
position: absolute;
left:50%;
top:50%;
margin-top:-100px;
margin-left:-100px;
}
2.使用 transform 变形
.box{
height:400px;
width:400px;
background-color: #ccc;
margin: 100px auto;
position: relative;
}
.son{
width:200px;
height:200px;
background-color: red;
position: absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
3.设置元素的定位位置,距离上、下、左、右都为0,margin设置为auto
.box{
height:400px;
width:400px;
background-color: #ccc;
margin: 100px auto;
position: relative;
}
.son{
width:200px;
height:200px;
background-color: red;
position: absolute;
left:0;
top:0;
right:0;
bottom: 0;
margin:auto
}
4.使用flex布局
.box{
height:400px;
width:400px;
background-color: #ccc;
margin: 100px auto;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width:200px;
height:200px;
background-color: red;
}
目标效果
就这