垂直居中
如果 .parent 的 height 不写,你只需要 padding: 10px 0; 就能将 .child 垂直居中; 如果 .parent 的 height 写死了,就很难把 .child 居中,以下是垂直居中的方法。 忠告:能不写 height 就千万别写 height。
table 方法
<table class="parent">
<tr>
<td class="child">...</td>
</tr>
</table>
<div class="table">
<div class="tr">
<div class="td">
<div class="child">...</div>
</div>
</div>
</div>
div.table {
display: table;
height: 600px;
}
div.tr {
display: table-row; //row 行
}
div.td {
display: table-cell; // cell 单位
vertical-align: middle; //vertical:垂直 align:排列 middle:中间
}
afrer before 方法
这个方法还有一个优化版本
<div class="parent">
<span class="before"></span>
<div class="child">...</div>
<span class="after"></span>
</div>
.parent {
height: 600px;
text-align: center;
}
.child {
display: inline-block;
width: 300px;
vertical-align: middle;
}
.parent .before {
display: inline-block;
height: 100%;
vertical-align: middle;
}
.parent .after {
display: inline-block;
height: 100%;
vertical-align: middle;
}
绝对定位方法
.parent {
height: 600px;
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
height: 100px;
width: 300px;
margin-top: -50px;
margin-left: -150px;
}
.parent {
height: 600px;
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.parent {
height: 600px;
position: relative;
}
.child {
position: absolute;
width: 300px;
height: 200px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
flex 方法
.parent {
height: 600px;
display: flex;
justify-content: center; //justify[ˈdʒʌstɪfaɪ]
align-items: center; //items[ˈaɪtəmz]
}
.child {
width: 300px;
}