水平垂直居中
# 面试
问:写出 div 水平垂直居中 的几种方式?
# flex方法
display: flex;
justify-content: center;
align-items: center;
1
2
3
2
3
# transform + 绝对定位
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
1
2
3
4
2
3
4
# 负margin + 绝对定位
.outer {
position: relative;
}
.inner {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
注意:此方法 需要知道 居中元素的 宽高
# calc + 绝对定位
position: absolute;
left: calc(50% - 50px);
top: calc(50% - 50px);
1
2
3
2
3
注意:此方法 需要知道 居中元素的 宽高
# margin: auto + 绝对定位
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
1
2
3
4
5
6
2
3
4
5
6
原理: 如果 left、right 和 width 都设置了具体值,并且没有占满横向空间,那么剩余空间就处于待分配状态,此时设置 margin: auto; 意味着把剩余的空间分配给 margin,并且左右均分,所以就实现了水平居中,垂直方向同理
- left: 0; right: 0; 相当于 width: 100%;
- top: 0; bottom: 0; 相当于 height: 100%;
# table-cell
<code>table-cell + vertical-align</code> 实现 垂直居中.
缺点:需要在外层div,设置width.
.out-box6 {
display: table-cell;
vertical-align: middle;
height: 200px;
width: 500px;
border: 1px solid red;
}
.inner-box6 {
width: 100px;
height: 100px;
margin: 0 auto;
border: 1px solid yellow;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
参考:https://liuyib.github.io/2020/04/07/css-h-and-v-center/#%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD
编辑 (opens new window)
上次更新: 2025/07/17, 07:17:44