垂直居中布局方法一:table-cell + vertical-align
<div class="parent">
<div class="child">Demo</div>
</div>
<style type="text/css">
.parent {
display: table-cell;
vertical-align: middle;
}
说明:兼容性好(IE 8以下版本需要调整页面结构至 table)
垂直居中布局方法二:absolute + transform
强大的absolute对于这种小问题当然也是很简单的
<div class="parent">
<div class="child">Demo</div>
</div>
<style type="text/css">
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
说明:
1.绝对定位脱离文档流,不会对后续元素的布局造成影响。但如果绝对定位元素是唯一的元素则父元素也会失去高度。
2.transform为 CSS3 属性,有兼容性问题
3.同水平居中,这也可以用margin-top实现,原理水平居中
垂直居中布局方法三:flex + align-items
如果说absolute强大,那flex只是笑笑,因为,他才是最强的。。。但它有兼容问题
<div class="parent">
<div class="child">Demo</div>
</div>
<style type="text/css">
.parent {
display: flex;
align-items: center;
}
</style>