方法1 margin
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
方法3 flex
.box {
display: flex;
background-color: red;
height: 400px;
width: 400px;
align-items: center;
justify-content: center;
}
.box2 {
height: 100px;
width: 100px;
background-color: pink;
}
<div class="box">
<div class="box2">
</div>
</div>
方法4 转换为inline
.box {
background-color: red;
height: 400px;
width: 400px;
text-align: center;
line-height: 400px;
}
.box2 {
display: inline;
background-color: pink;
}
<div class="box">
<div class="box2">
内容内容
</div>
</div>