水平居中
- 需要居中 inline 或者 inline-* 元素(如文字或者链接)?
- 需要居中 block 类的元素?
- 需要居中多个 block 元素?
垂直居中
- 需要居中 inline 或者 inline-* 元素(如文字或者链接)?
- 需要居中 block 类的元素?
既水平又垂直
- 固定宽高
- 不固定宽高
使用 flexbox
- 水平居中
- 水平居中 inline 或者 inline-* 元素
1. 你可以轻松的在一个 block 元素中水平居中一个 inline 元素,以下代码对 inline,inline-block,inline-table 和 inline-flex 等有效
1 | .parent { |
2. 水平居中 block 类的元素
1 | 在 block 元素被设定固定宽度的情况下,可以使用设置元素 margin-left 和 margin-right 的值为 auto 的方法实现水平居中。 |
3. 水平居中多个 block 类的元素
1 | 通过 inline-block实现 |
1 | 通过 flexbox 实现 |
4. 垂直居中 inline 或者 inline-* 元素
1 | 单行 |
1 | 多行 |
如果上述方法不能使用,你可以尝试使用 flexbox,一个单独的 flexbox 子元素可以轻易的在其父元素中居中。谨记,这种方法需要父元素有固定的高度。1
2
3
4
5
6.parent {
display: flex;
justify-content: center;
flex-direction: column;
height: 400px;
}
如果上述两种方式均不能使用,你可以使用“幽灵元素”技术,这种方法采用伪元素 ::before 撑开高度 ,文字垂直居中。1
2
3
4
5
6
7
8
9
10
11
12
13
14.parent {
position: relative;
}
.parent::before {
content: " ";
display: inline-block;
height: 100%;
width: 1%;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
5. 垂直居中 block 类的元素
已知元素高度1
2
3
4
5
6
7
8
9.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}
未知元素高度1
2
3
4
5
6
7
8.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
使用 flexbox1
2
3
4
5.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
6. 既水平又垂直
固定宽高1
2
3
4
5
6
7
8
9
10
11
12
13
14
15.parent {
position: relative;
}
.child {
width: 300px;
height: 100px;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
margin: -70px 0 0 -170px;
}
不固定宽高1
2
3
4
5
6
7
8
9.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用 flexbox1
2
3
4
5.parent {
display: flex;
justify-content: center;
align-items: center;
}