Summary and Comparison of CSS Mainstream Layouts (2) Vertical Center Alignment

Summarize the different implementations of vertical center alignment in several mainstream layouts and the comparisons between them.

Father

Code

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
<!DOCTYPE html>
< html long = "and" >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#parent {
width: 200px;
height: 600px;
background-color: aliceblue;
display: table-cell;
vertical-align: middle;
}

#child {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="parent">
<div id="child"></div>
</div>
</body>
</html>

Principle

vertical-align

CSS 的属性 vertical-align 用来指定行内元素(inline)或表格单元格(table-cell)元素的垂直对齐方式。

Note that’vertical-align 'only works for inline elements and table cell elements: it cannot be used for vertical alignment块级元素

You can see the specific value of vertical-align.MDN, just to mention one point here, that is, for inline elements and table cells, their value ranges are not exactly the same, even if the same value will have different meanings.

display

This property was introduced in the previous blog, this time we are using its table-cell value

This value will make the current element behave like a td. The content of td can be centered text or vertically centered.

Advantages

Good compatibility

Disadvantage

Vertical-align is inherited

子posititon:absolute

Code

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
<!DOCTYPE html>
< html long = "and" >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#parent {
width: 200px;
height: 600px;
background-color: aliceblue;
position: relative;
}

#child {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
transform: translateY(-50%);
top: 50%;
}
</style>
</head>
<body>
<div id="parent">
<div id="child"></div>
</div>
</body>
</html>

Principle, Advantages, Disadvantages

You can check mine for this principle.上一篇博客The second plan of the centered text is the same.