1.盒子脱离标准流,绝对定位4个方向为0,即可让小盒子水平垂直居中
.box {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
.son {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
width: 200px;
height: 200px;
background-color: blue;
margin: auto;
}
2.margin+位移固定宽高居中
.box {
width: 400px;
height: 400px;
background-color: pink;
}
.son{
width: 200px;
height: 200px;
margin-left: 100px;
transform: translate(0,50%);
background-color: blue;
}
3.flex布局盒子居中
.box {
width: 400px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
background-color: pink;
}
.son {
width: 200px;
height: 200px;
background-color: blue;
}
4.位移居中(transform)
.box {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
.son {
position: relative;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: blue;
}
5.table-cell居中
.box {
width: 400px;
height: 400px;
background-color: pink;
display: table-cell;
vertical-align: middle;
}
.son {
width: 200px;
height: 200px;
background-color: blue;
margin: 0 auto;
}