垂直居中实现方式总结

在网页制作过程中,我们经常要用到图片、文字的垂直居中。今天就总结一下垂直居中的方法。

方法一 利用 line-height 实现垂直居中

1
2
3
4
5
6
7
8
9
10
11
#example1 {
height: 100px;
line-height: 100px;
background: #161616;
color: #fff;
width: 200px;
}
<div id="example1">
单行文字垂直居中
</div>

示例:

单行文字垂直居中

这种方法适用于单行文本垂直居中,如果文本内容太长,出现了换行,换行后的内容会溢出。

方法二 利用 display: table 实现垂直居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#example2 {
height: 100px;
background: #161616;
color: #fff;
width: 400px;
overflow: hidden;
display: table;
}
#example2 .inner{
display: table-cell;
vertical-align: middle;
height: 50px;
background:#999;
}
<div id="example2">
<div class="inner">块区域垂直居中</div>
</div>

示例:

块区域垂直居中

方法三 margin 填充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#example3 {
height: 100px;
background: #161616;
color: #fff;
width: 400px;
overflow: hidden;
}
#example3 .inner{
margin-left: auto;
margin-right: auto;
margin-top: calc((100px - 50px)/2);
height: 50px;
background:#999;
}
<div id="example3">
<div class="inner">块区域垂直居中</div>
</div>

示例:

块区域垂直居中

这种方法需要知道内外容器的大小

方法四 经典 absolute 布局上下文垂直居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#example4 {
width: 400px;
height: 100px;
background: #161616;
color: #fff;
position: relative;
}
#example4 .inner{
height: 50px;
width: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -25px;
margin-left: -100px;
background:#999;
}
<div id="example4">
<div class="inner">块区域垂直居中</div>
</div>

示例:

块区域垂直居中

这种方法内部容器的宽高,外部容器的宽高可以不定

方法五 Css3下 absolute 布局上下文垂直居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#example5 {
width: 400px;
height: 100px;
background: #161616;
color: #fff;
position: relative;
}
#example5 .inner{
position: absolute;
left: 50%;
top: 50%;
background: #999;
transform: translate(-50%, -50%);
}
<div id="example5">
<div class="inner">块区域垂直居中</div>
</div>

示例:

块区域垂直居中

这种方法内外容器都可以是不定的

方法六 利用margin:auto 居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#expample6 {
width: 400px;
height: 100px;
background: #eee;
position: relative;
}
#expample6 .inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 50px;
width: 70%;
background: #aaa;
color:#222;
}
<div id="expample6">
<div class="inner">Content here</div>
</div>

示例:

块区域垂直居中

方法七 利用 Flex布局 居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#expample7 {
width: 400px;
height: 100px;
background: #eee;
display: flex;
justify-content: center;
align-items: center;
}
#expample7 .inner {
height: 50px;
width: 70%;
background: #aaa;
color:#222;
}
<div id="expample7">
<div class="inner">Content here</div>
</div>

示例:

块区域垂直居中
坚持原创技术分享,您的支持将鼓励我继续创作!