css布局之垂直居中

今天总结一下css中垂直居中的方法

1.display:table-cell

外容器定宽高,设置display:table,内容器外套一层标签,设置display:table-cell;vertical-align:middle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<style>
.container{
width: 100px;
height: 100px;
background-color: yellow;
display: table;
}
.container-nav{
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="container-nav">
<span>middle</span>
</div>
</div>
</body>
</html>

2.line-height

若内层只有一行,可以设line-height与容器高度相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<style>
.container{
width: 100px;
height: 100px;
background-color: yellow;
text-align: center;
}
.container span{
line-height: 100px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<span>middle</span>
</div>
</body>
</html>

3.给出一致的padding-top和padding-bottom

4.margin-top为负的高度的一半

5.margin

内容器设定高度,设置绝对定位,top,left,right,bottom都为0,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
24
25
26
27
<html>
<head>
<style>
.container{
width: 100px;
height: 100px;
background-color: yellow;
position: relative;
}
.container-nav{
height: 50px;
background-color: red;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="container-nav"> </div>
</div>
</body>
</html>

6.transform

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
<head>
<style>
.container{
width: 100px;
height: 100px;
background-color: yellow;
position: relative;
}
.container-nav{
height: 50px;
background-color: red;
width: 50%;
margin: auto;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="container">
<div class="container-nav"> </div>
</div>
</body>
</html>

7.伪元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html>
<head>
<style>
.container{
width: 100px;
height: 100px;
background-color: yellow;
text-align: center;
}
.container-nav,.container:after{
display: inline-block;
vertical-align: middle;
background-color: red;
}
.container-nav{
width: 50px;
height: 50px;
}
.container:after{
content: '';
height: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="container-nav"> </div>
</div>
</body>
</html>