前言
水平垂直居中是布局中经常使用到的样式,有许多方法都可以实现。本文介绍了利用绝对定位、table-cell + inline-block、flex、grid 实现水平垂直居中的方式。
水平垂直居中
页面 HTML 代码如下所示:
<div class="parent">
<div class="child">child</div>
</div>
父子元素样式:
.parent {
border: 1px solid;
width: 200px;
height: 200px;
}
.child {
width: 100px;
height: 100px;
background: red;
}
使用
table布局、父子元素同宽高 +padding或margin也能实现水平垂直居中,但现在有更好的方法替代,本文不做介绍。
绝对定位实现
- 父元素设置
position: relative;让子元素定位到父元素上。
.parent {
position: relative;
}
absolute + margin: auto
- 绝对定位盒子模型包含块的宽度 =
left+right+width+padding+margin。 - 我们将
left和right设置为 0,margin设置为 auto,使得自动居中。 - 垂直方向同理。
- 该方法适用已知子元素宽高的盒子,中间块的宽度和高度是必须的,否则会自动铺满(默认值为 auto)。
.child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
absolute + 负 margin
- 先使用绝对定位定位到父元素中间,然后使用负 margin 将自身中心调整至定位位置。
- 该方法适用已知子元素宽高的盒子。
.child {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
absolute + transform
- 与上一方法思路相同,但使用
transform同样可以实现绝对定位后对自身位置的偏移。 - 无需知道子元素的具体长宽。
.child {
position: absolute;
left: 50%;
top: 50%;
transfrom: translate3d(-50% -50%);
}
absolute + calc
- 强大的计算属性让样式样式书写如虎添翼,直接将子元素定位到对应位置。
- 该方法适用已知子元素宽高的盒子。
- 需 CSS3 兼容。
.child {
position: absolute;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
table-cell + inline-block
display: table-cell;可以把普通元素变为table元素的实现效果。- 比完全使用
table布局减少大量冗余代码。 - 但子元素内文字也会自动居中,需要再次调整。
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}
flex 实现
- 强大高效的现代布局方案。
.parent {
display: flex;
justify-content: center;
align-items: center;
}
grid 实现
- 强大高效的现代布局方案。
.parent {
display: grid;
}
.child {
justify-self: center;
align-self: center;
}
参考资料
前端面试题之CSS篇 (yuque.com)
css经典布局系列一——垂直居中布局 - 掘金
CSS实现水平垂直居中的10种方式 - 掘金