1、定位+margin:通过子绝父相和外边距实现
代码:
<style>
{
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
width: 200px;
height: 200px;
background-color: red;
}
</style>
2、定位+transform:translate(位移)
代码:
.father {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
background-color: red;
}
3、定位+margin:auto
代码:
.father {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
.son {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: red;
}
4、弹性布局让盒子居中(flex)
代码:
<style>
.father {
width:400px;
height:400px;
background-color:pink;
/弹性容器/
display;flex;
justify-content:center;
align-items:center;
}
.son {
width:200px;
height:200px;
background-color:green;
}
</style>