水平垂直居中的几种方式-案例
# 水平垂直居中的几种方式-案例
- 各种主流写法(Flex、Grid、定位、transform 等)
- 典型代码 + 适用场景 + 注意点
- 面试可用讲解总结
# 一、Flex 布局居中(最推荐、最常用)
- 现代布局首选,语义清晰。
- 不受子元素宽高影响。
- 可用于响应式、自适应场景。
# 二、Grid 布局居中(现代方案)
- Grid 的
place-items: center是最简写法。 - 对内容多、需要多维控制(如多行多列对齐)时更优。
- Flex 更适合一维布局,Grid 更适合二维布局。
.parent {
display: grid;
place-items: center; /* 相当于 justify-items + align-items */
height: 200px;
border: 1px solid #ccc;
}
1
2
3
4
5
6
2
3
4
5
6
# 三、绝对定位 + transform 居中(经典通用)
- 经典做法,兼容性极好(IE8+)。
- 不依赖父元素布局属性。
- 缺点:如果子元素大小变化或需要流式布局,不够灵活。
.parent {
position: relative;
height: 200px;
border: 1px solid #ccc;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #10b981;
color: white;
padding: 10px 20px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 四、绝对定位 + margin:auto 居中(固定宽高)
- 子元素必须有固定宽高。
margin: auto会在四个方向自动平分空白。- 常用于弹窗、模态框。
.parent {
position: relative;
height: 200px;
}
.child {
position: absolute;
top: 0; bottom: 0;
left: 0; right: 0;
margin: auto;
width: 100px;
height: 50px;
background: #ef4444;
color: white;
text-align: center;
line-height: 50px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 五、行内元素 + text-align + line-height(适合单行文本)
- 仅适用于单行文字,不适合多行内容或复杂块级元素。
.parent {
height: 100px;
line-height: 100px; /* 垂直居中(仅单行文本) */
text-align: center; /* 水平居中 */
border: 1px solid #ccc;
}
1
2
3
4
5
6
2
3
4
5
6
# 六、table-cell 居中(旧兼容方案)
- 兼容性非常好(IE7+)。
- 不推荐在现代布局中使用,但面试中可以提到作为历史方案。
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
height: 200px;
width: 100%;
border: 1px solid #ccc;
}
.child {
display: inline-block;
background: #3b82f6;
color: white;
padding: 10px 20px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 七、CSS Grid + minmax() + auto-fit(更灵活的居中布局)
place-content: center可同时控制整个内容块在父容器中居中。- 适合响应式卡片、空状态页等。
.parent {
display: grid;
grid-template-columns: minmax(auto, 1fr);
place-content: center;
height: 200px;
border: 1px solid #ccc;
}
.child {
background: #f59e0b;
padding: 10px 20px;
color: #fff;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 八、面试总结模板
Vue 或 React 项目里我常用 Flex 布局 来实现水平垂直居中: 父容器
display:flex; justify-content:center; align-items:center;即可。 如果遇到老项目或需要精确控制位置,我也会用 绝对定位 + transform。 另外在现代浏览器中,CSS Grid 的 place-items:center 是最简写法。 不同方案各有优劣:
- Flex:最通用
- Grid:最简洁
- transform:最兼容
# Bonus:响应式+全屏居中实战案例(常用于加载页)
<template>
<div class="center-box">
<h2>正在加载中...</h2>
</div>
</template>
<style scoped>
.center-box {
position: fixed;
inset: 0; /* 等价于 top:0; right:0; bottom:0; left:0; */
display: flex;
justify-content: center;
align-items: center;
background: rgba(255,255,255,0.9);
z-index: 9999;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上次更新: 2025/11/25, 03:24:47