# 垂直居中布局
居中布局可以利用
margin: 0 auto
或者inline-block
内联块元素等等,但是垂直效果,我们改怎么来做呢?所有源码 (opens new window)在此
常见的 HTML 格式为
<div class="parent_0">
<div class="child_0"></div>
</div>
1
2
3
2
3
# 绝对定位和 margin
.parent_0 {
position: relative;
height: 500px;
background-color: bisque;
}
.child_0 {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
background-color: red;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
需要计算子元素的半宽高
# 绝对定位和 transform
.parent_1 {
position: relative;
height: 500px;
background-color: bisque;
}
.child_1 {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 330px;
transform: translate3d(-50%, -50%, 0);
background-color: red;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
不用计算,但是兼容性需要考虑
# 绝对定位的另类用法
.parent_2 {
position: relative;
height: 500px;
background-color: bisque;
}
.child_2 {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 50%;
height: 30px;
background-color: red;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
不用计算子元素,兼容性好,子元素高宽完美自适应,可以百分比,可以任意高宽
常见于弹出框,遮罩
# flex 布局
.parent_3 {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
background-color: bisque;
}
.child_3 {
width: 200px;
height: 330px;
background-color: red;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
简单高效,父级需要指定高度;兼容性需要考虑
# inline-block 属性与伪类元素
.parent_4 {
height: 500px;
font-size:0; /* 避免inline-block之间产生间隔 */
text-align: center;
}
.parent_4::after {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.child_4 {
display: inline-block;
width: 200px;
height: 200px;
vertical-align: middle;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
兼容性较好
# table 与 table-cell 布局
.parent_5 {
display: table;
width: 100%;
height: 500px;
}
.child_5 {
display: table-cell;
vertical-align: middle;
}
.child_5 .content {
width: 200px;
height: 200px;
margin: 0 auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
需要改动 HTML 格式,兼容性较好
<div class="parent_bg parent_5">
<div class="child_5">
<div class="child_bg content">垂直居中</div>
</div>
</div>
1
2
3
4
5
2
3
4
5
# 总结
多种写法,需要考虑到:
- 兼容性
- 居中元素是否需要自适应宽高
- 交互
JavaScript
的效果