对于verticle-align,有一个非常全面的理解:张鑫旭的解释;
关于flex:设为Flex布局以后,子元素的float、clear和vertical-align属性将失效
- flex:水平和垂直居中对齐 : flex + justify-content + align-items
只需设置父节点属性,无需设置子元素
<div class="parent">
<div class="child">Demo</div>
</div>
<style>
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /*垂直居中*/
}
</style>
只设置 justify-content: center
未设置align-items: center
子元素高度将被拉伸至与父元素高度一致
缺点:有兼容性问题
2. table水平垂直居中 : table-cell + text-align + vertical-align +inline-block
<div class="parent">
<div class="child">Demo</div>
</div>
<style>
.parent {
text-align: center;//水平居中
display: table-cell;
vertical-align: middle;//垂直居中
}
.child {
display: inline-block;//防止块级元素宽度独占一行,内联元素可不设置
}
</style>
vertical-align的百分比值不是相对于字体大小或者其他什么属性计算的,而是相对于line-height计算的
3.absolute+transform
水平垂直居中
<div class="parent"> <div class="child">Demo</div> </div> <style> .parent { position: relative; } .child { position: absolute; //子元素相对于父元素 left: 50%; top: 50%; transform: translate(-50%, -50%); } </style>
relative+absolute + negative margin
.parent{
position:relative;
}
.child{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
缺点:需设置子元素宽高
relative+absolute + negative margin
.parent{
position:relative;
}
.child{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
缺点:需设置子元素宽高
relative+absolute + negative margin
.parent{
position:relative;
}
.child{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
缺点:需设置子元素宽高
水平居中
- 对于行内元素(inline):text-align: center;
- 对于块级元素(block):设置宽度且 marigin-left 和 margin-right 是设成 auto
- 对于多个块级元素:对父元素设置 text-align: center;,对子元素设置 display: inline-block;;或者使用 flex 布局
垂直居中
对于行内元素(inline)
- 单行:设置上下 pandding 相等;或者设置 line-height 和 height 相等
- 多行:设置上下 pandding 相等;或者设置 display: table-cell; 和 vertical-align: middle;;或者使用 flex 布局;或者使用伪元素
对于块级元素(block):下面前两种方案,父元素需使用相对布局
- 已知高度:子元素使用绝对布局 top: 50%;,再用负的 margin-top 把子元素往上拉一半的高度
- 未知高度:子元素使用绝对布局 position: absolute; top: 50%; transform: translateY(-50%);
- 使用 Flexbox:选择方向,justify-content: center;
原文链接:https://github.com/hawx1993/tech-blog/issues/12