HTML
<div class="parent answer-1">
<div></div>
</div>
CSS
.parent {
width: 800px;
height: 800px;
border: 1px solid red;
}
.parent div {
width: 200px;
height: 200px;
border: 1px solid red;
} /*方法1:dispaly:table-cell*/
.answer-1 {
display: table-cell;
vertical-align: middle;
}
.answer-1 div {
margin: auto;
}
/*方法2:绝对定位(高度必须固定)*/
.answer-2 {
position: relative;
}
.answer-2 div {
position: absolute;
/*垂直居中*/
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
/*水平居中*/
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
/*方法3:弹性布局(高度可不固定)*/
.answer-3 {
display: flex;
/*垂直居中*/
align-items: center;
/*水平居中*/
justify-content: center;
}
/*方法4:绝对定位 + 2d转换(高度可不固定)*/
.answer-4 {
position: relative;
}
.answer-4 div {
position: absolute;
/*垂直居中*/
top: 50%;
/*水平居中*/
left: 50%;
transform: translate(-50%,-50%);
}