1.flex布局:
.box{
display: flex;
flex-direction: row; /* 子元素横向排列 */
justify-content: center;/* 水平居中 */
align-items: center;/* 垂直居中 */
border: solid 1px yellow;
border: solid 1px red;
height: 400px;
width: 400px;
}
.div{
width: 100px;
height: 100px;
border: solid 1px #FFC0CB;
}
<div class="box">
<div class="div">aa</div>
<div class="div">bb</div>
</div>
效果:
2.用定位和translate:
.box{
height: 400px;
width: 400px;
position: relative;
border: solid 1px red;
}
.div{
width: 100px;
height: 100px;
border: solid 1px #FFC0CB;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
<div class="box">
<div class="div">aa</div>
</div>
效果:
3.直接给子元素设置margin:auto;
.center {
border: solid 1px #f00;
position: fixed;
width: 100px;
height: 100px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
<div class="center">000</div>
效果:
4.margin设为负值:
.center {
border: solid 1px #f00;
position: fixed;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
<div class="center">000</div>
效果:
5.父级采用table-cell布局:
.center {
border: solid 1px #f00;
display: inline-block;
}
.father {
width: 200px;
height: 200px;
border: solid 1px #f00;
display: table-cell;
vertical-align: middle;
text-align: center;
}
<div class="father"> <div class="center">000</div></div>
效果: