CSS垂直居中

HTML 框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
#box {
width: 300px;
height: 300px;
background-color: #ddd;
}
#child {
width: 200px;
height: 100px;
background-color: orange;
}
</style>
<div id="box">
<div id="child">target</div>
</div>

绝对定位 + 负外边距 1

1
2
3
4
5
6
7
8
#box {
position: relative;
}
#child {
position: absolute;
top: 50%;
margin: -50px 0 0 0;
}

缺点:需要知道目标元素的高度

绝对定位 + 负外边距 2

1
2
3
4
5
6
7
8
9
#box {
position: relative;
}
#child {
height: 30%;
position: absolute;
top: 50%;
margin: -15% 0 0 0;
}

绝对定位 + transform

1
2
3
4
5
6
7
8
#box {
position: relative;
}
#child {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}

绝对定位 + margin: auto

1
2
3
4
5
6
7
8
9
10
#box {
position: relative;
}
#child {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
line-height: 100px;
}

flex

1
2
3
4
#box {
display: flex;
align-items: center;
}