<div class="box">
<div class="child"></div>
</div>
方法1:宽度和高度已知的。
.box{
width: 400px;
height: 200px;
position: relative;
background: red;
}
.child{
width: 200px;
height: 100px;
background: #000;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -50px;
}
方法2:兼容性最大
.box{
width: 400px;
height: 200px;
position: relative;
background: red;
}
.child{
width: 200px;
height: 100px;
background: #000;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3.flex
.box{
width: 400px;
height: 200px;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
4.平移+定位
.box{
width: 400px;
height: 200px;
position: relative;
background: red;
}
.child{
width: 200px;
height: 100px;
background: #000;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
5.table-cell
.box{
width: 400px;
height: 200px;
position: relative;
background: red;
display: table-cell;
vertical-align: middle;
}
.child{
width: 200px;
height: 100px;
background: #000;
margin: 0 auto;
}