发布于 

CSS 垂直居中的几种方式

只提供核心代码,多余代码已被省去。

padding

适用于 parent 的高度不确定的情况

1
2
3
4
5
.parent {
padding: 20px 0;
}

.child {}

flex

1
2
3
4
5
6
7
.parent {
display: flex;
justify-content: center;
align-items: center;
}

.child {}

absolute margin auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
position: relative;
}

.child {
position: absolute;
margin: auto;
width: 300px;
height: 200px;
top: 0;
bottom: 0;
left: 0;
right: 0;
}

注意:

  1. child 的宽高都必须是确定值
  2. 可用 inset: 0 代替 top: 0; bottom: 0; left: 0; right: 0;

absolute translate

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

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

grid

1
2
3
4
5
6
7
.parent {
display: grid;
}

.child {
place-self: center;
}

(●'◡'●)ノ♥