方案一:利用 display: inline-block; vertical-align: middle;
<div class="box">
<div></div>
<span></span>
</div>
.box {
width: 500px;
height: 500px;
background-color: red;
text-align: center;
}
.box div {
width: 200px;
height: 200px;
background-color: orange;
display: inline-block;
vertical-align: middle;
}
.box span {
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
}
方案二:定位法(1)
<div class="box">
<div></div>
</div>
.box {
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.box div {
width: 200px;
height: 200px;
background-color: orange;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
方案三:定位法(2)
<div class="box">
<div></div>
</div>
.box {
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.box div {
width: 200px;
height: 200px;
background-color: orange;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
方案四: 弹性布局
<div class="box">
<div></div>
</div>
.box {
width: 500px;
height: 500px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.box div {
width: 200px;
height: 200px;
background-color: orange;
}
方案五:利用 display: table-cell; vertical-align: middle;
<div class="box">
<div></div>
</div>
.box {
width: 500px;
height: 500px;
background-color: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box div {
width: 200px;
height: 200px;
background-color: orange;
display: inline-block;
}
方案六:利用translate位移
<div class="box">
<div></div>
</div>
.box {
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.box div {
width: 200px;
height: 200px;
background-color: orange;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
效果图如下: