Ryan Shang

生死看淡,不服就干

0%

CSS垂直居中

1. 行内元素

1
2
3
4
5
6
.parent {
height: X; /* X为一个绝对高度 */
}
.child {
line-hight: X;
}

2. Table

1
2
3
4
5
6
7
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}

3. 绝对定位(left+height)

1
2
3
4
5
6
7
8
9
10
.parent {
position: releative;
}

.child {
position: absolute;
height: X; /* X为一个绝对高度 */
top: 50%;
margin-top: -0.5*X
}

4. 绝对定位(transform)

1
2
3
4
5
6
7
8
9
.parent {
position: releative;
}

.child {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}

5. 绝对定位(top+bottom)

1
2
3
4
5
6
7
8
9
10
.parent {
position: releative;
}

.child {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}

6. Flex布局

1
2
3
4
.parent {
display: flex;
align-items: center;
}

7. Grid布局

1
2
3
4
.parent {
display: grid;
align-items: center;
}