1、absolute + transform
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
position: relative;
}
.box {
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2、absolute + margin:auto
- 必须定 width、height
- 否则,内部width、height等于外部宽、高
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
position: relative;
}
.box {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: powderblue;
}
3、display: table-cell
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
width: 100px;
height: 100px;
border: 1px solid blue;
display: inline-block;
}
4、display:flex
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.box {
height: 100px;
width: 100px;
border: 1px solid blue;
}
5、display: grid
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
display: grid;
}
.box {
justify-self: center;
align-self: center;
background-color: powderblue;
}