3种垂直居中布局的方法
上篇文章说到常见css布局水平居中的方法,前端开发css布局还有垂直居中,也是很常见的布局方法,本文分享3种垂直居中布局的方法,table-cell + vertical-align、absolute + transform、flex + align-items,很常见,很实用。

垂直居中布局方法一:table-cell + vertical-align
<div class="parent">
<div class="child">Demo</div>
</div>
<style type="text/css">
.parent {
display: table-cell;
vertical-align: middle;
}
</style>说明:兼容性好(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>除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.cn/divcss/177.html
原文地址:https://tangjiusheng.cn/divcss/177.html
大家都在看
