我目前想到的有以下几种,经过实践认证过:
1、子元素设置margin:auto
<div class="father">
<div class="child"></div>
</div>
.father {
width: 400px;
height: 400px;
border: 1px solid black;
}
.child {
margin: auto;
width: 60px;
height: 60px;
background-color: red;
}
2、父元素设置flex布局,主轴(justify-content)和次轴(align-items)都垂直居中
<div class="father">
<div class="child"></div>
</div>
.father {
display: flex;
width: 400px;
height: 400px;
border: 1px solid black;
justify-content: center;
align-items: center;
}
.child {
width: 60px;
height: 60px;
background-color: red;
}
3、父元素设置相对定位,子元素设置绝对定位,子元素的left和top设置为50%(相对于父元素),再设置margin-top/left为负数子元素的高宽。
<div class="father">
<div class="child"></div>
</div>
.father {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.child {
width: 60px;
height: 60px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
margin-left:-30px;
margin-top:-30px;
/* 或者上面四行用用下面的calc计算 */
/* left: calc(50% - 30px);
top: calc(50% - 30px); */
/* 或者margin-left和margin-top的2行用变换translate或者transform来计算 */
/* translate: -50% -50%; */
/* transform: translate(-50%,-50%); */
}
4、父元素设置table-cell布局,text-align和vertical-align为center和middle,子元素设置为inline-block布局。
<div class="father">
<div class="child"></div>
</div>
.father {
width: 400px;
height: 400px;
border: 1px solid black;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
width: 60px;
height: 60px;
background-color: red;
display: inline-block;
}