0%

css-vertical-align-center

简介

居中是CSS中永恒的话题,而垂直居中则是这个永恒话题中的重中之重,无论是日常工作,还是面试,你永远都绕不开垂直居中,今天咱们来详细讲解一下垂直居中。我们不会简单的罗列css样式,而是按不同分类来处理,这样更有利于理解。

inline或者inline-*元素的垂直居中(本质是文本垂直居中)

padding-top = padding-bottom

inline元素是指不会独占一行的元素,比如span, a, img等等。inline元素的垂直居中,可以通过设置padding-top和padding-bottom为相同的值来实现垂直居中。考虑如下html代码:

1
<span>This is a span</span>

我们先设置个背景色,方便查看span元素的高度,然后设置padding-toppadding-bottom为16px,这样span元素内的文本就垂直居中了。此方案也适用于多行文本。

1
2
3
background-color: green;
padding-top: 16px;
padding-bottom: 16px;

line-height = height

如果是对block element里面的文本垂直居中(比如div, p内的文本),那么可以尝试设置line-height等于height,这样也可以实现垂直居中。- 此方案不适用于多行文本。(多行文本时,文本会超出容器外,因为line-height本质上设置的是行与行之间的垂直距离)

1
<div class="content">This is a div</div>
1
2
3
background-color: green;
height: 60px;
line-height: 60px;

需要注意的是span属于inline元素,height对于inline元素是无效的。inline元素的宽度和高度由内容决定,所以heightwidth对于inline元素是无效的。但是line-height对于inline元素是有效的。

block elements的垂直居中

以如下代码为例,我们需要将子元素child垂直居中于父元素parent

1
2
3
<div class="parent">
<div class="child">Child</div>
</div>

此时,又分为两种情况,一种是我们知道子元素的高度,另一种是我们不知道子元素的高度。这两种情况有不同的处理方式。

知道元素的高度

  1. 设置父元素position: relative, 子元素position: absolute
  2. 设置子元素height: 100px, 这个是必须的,此条件就是元素高度已知。
  3. 设置子元素top: 50%, margin-top: -height/2(50px)
1
2
3
4
5
6
7
8
9
10
11
12
13
.parent {
position: relative;
height: 400px;
width: 100%;
background-color: red;
}
.child {
position: absolute;
height: 100px; /* You know the height of the element */
top: 50%;
margin-top: -50px; /* half of element height */
background-color: green;
}

不知道元素高度

大多数情况下,元素的高度是未知的,这时候可以使用使用transform: translateY(-50%);代替margin-top: -50px;

1
2
3
<div class="parent">
<div class="child">Child</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
.parent {
position: relative;
height: 400px;
background-color: red;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: green;
}

使用table-cell

如果你不在乎子元素会被拉伸并填满父元素的话,可以使用table-cell来实现垂直居中。

1
2
3
<div class="parent">
<div class="child">Child</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
.parent {
position: relative;
display: table; /* 父元素使用table布局 */
height: 400px;
background-color: red;
}
.child {
display: table-cell; /* 子元素使用table-cell布局 */
vertical-align: middle; /* 垂直居中 */
background-color: green;
}

使用flex布局

这是目前来讲最方便的方式了,使用flex布局可以轻松实现水平和垂直居中。首先将父元素设置为flex布局,然后设置flex-direction: column;将布局方式改为纵向排列(默认是横向排列),然后设置justify-content: center;即可实现垂直居中。

1
2
3
<div class="parent">
<div class="child">Child</div>
</div>
1
2
3
4
5
6
7
.parent {
display: flex;
flex-direction: column;
justify-content: center;
height: 400px;
background-color: red;
}

References

  1. https://css-tricks.com/centering-css-complete-guide/