1. flex
.parent{
height: 500px;
width: 500px;
border: 1px solid red;
display: flex;
align-items: center;
justify-content: center;
}
.child{
height: 80px;
width: 80px;
background-color: #bbb;
}
2. tabel-cell
.parent{
height: 500px;
width: 500px;
border: 1px solid red;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child{
display: inline-block;
height: 80px;
width: 80px;
background-color: #bbb;
}
3. 定位 + transform
.parent{
height: 500px;
width: 500px;
border: 1px solid red;
position: relative;
}
.child{
height: 80px;
width: 80px;
background-color: #bbb;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
4. margin + transform
.parent{
height: 500px;
width: 500px;
border: 1px solid red;
}
.child{
height: 80px;
width: 80px;
background-color: #bbb;
margin: 50% 0 0 50%;
transform: translate(-50%, -50%);
}
5. 定位 + 负margin
.parent{
height: 500px;
width: 500px;
border: 1px solid red;
position: relative;
}
.child{
height: 80px;
width: 80px;
background-color: #bbb;
position: absolute;
left: 50%;
top: 50%;
margin: -40px 0 0 -40px;
}
参考资料