1. 定位+负margin
.box1 {
width: 200px;
height: 200px;
background: pink;
position: relative;
}
.box2 {
width: 50px;
height: 50px;
background: steelblue;
position: absolute;
left: 50%;
top: 50%;
margin-top: -25px;
margin-left: -25px;
}
2. 定位+margin auto
.box1 {
width: 200px;
height: 200px;
background: pink;
position: relative;
}
.box2 {
width: 50px;
height: 50px;
background: steelblue;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
3. 定位+transform
.box1 {
width: 200px;
height: 200px;
background: pink;
position: relative;
}
.box2 {
width: 50px;
height: 50px;
background: steelblue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
4. flex布局
.box1 {
width: 200px;
height: 200px;
background: pink;
display: flex;
justify-content: center;
align-items: center;
}
.box2 {
width: 50px;
height: 50px;
background: steelblue;
}
5. table布局
.box1 {
width: 200px;
height: 200px;
background: pink;
display: table;
padding: 20px
}
.box2 {
width: 50px;
height: 50px;
background: steelblue;
display: table-cell;
vertical-align: middle;
text-align: center;
}
6. grid布局
.box1 {
width: 200px;
height: 200px;
background: pink;
display: grid;
}
.box2 {
width: 50px;
height: 50px;
background: steelblue;
align-self: center;
justify-self: center;
}