第一种利用flex布局实现
.div1 {
width: 200px;
height: 200px;
border: 1px solid #333;
display: flex;
align-items: center;
justify-content: center;
}
.div1 div {
width: 100px;
height: 100px;
background-color: red;
}
第二种用定位和转换实现
.div2 {
width: 200px;
height: 200px;
border: 1px solid #333;
position: relative;
}
.div2 div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
第三种用表格布局实现
.div3 {
width: 200px;
height: 200px;
border: 1px solid #333;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.div3 div {
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
}
第四种用定位和外边距auto实现
.div4 {
width: 200px;
height: 200px;
border: 1px solid #333;
position: relative;
}
.div4 div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}