一,dom元素垂直居中
flex来实现
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
<html>
<head>
<meta charset='utf-8'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
#out{
background: red;
width: 600px;
height: 300px;
display: flex;
}
#in{
background: blue;
width: 50%;
height: 50%;
display: inline-block;
align-self: center;
}
</style>
</head>
<body>
<div id='out'>
<div id='in'></div>
</div>
</body>
</html>通过伪元素:before 实现
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
31
32
33
34
<html>
<head>
<meta charset='utf-8'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
#out{
background: red;
width: 600px;
height: 300px;
display: block;
}
#out::before{
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
#in{
background: blue;
width: 50%;
height: 50%;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div id='out'>
<div id='in'></div>
</div>
</body>
</html>通过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
<html>
<head>
<meta charset='utf-8'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
#out{
background: red;
width: 600px;
height: 300px;
}
#in{
background: blue;
width: 50%;
height: 50%;
position: relative;
top:50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div id='out'>
<div id='in'></div>
</div>
</body>
</html>通过position来实现
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>
<meta charset='utf-8'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
#out{
background: red;
width: 600px;
height: 300px;
position: relative;
}
#in{
background: blue;
width: 50%;
height: 50%;
position: absolute;
top:50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div id='out'>
<div id='in'></div>
</div>
</body>
</html>