使用Flexbox实现水平垂直居中需设置父容器display: flex,justify-content: center实现水平居中,align-items: center实现垂直居中,且容器需有明确高度,适用于模态框、登录页等场景。

使用CSS弹性盒子布局(Flexbox)实现水平垂直居中,最常用的方法是结合 justify-content 和 align-items 两个属性。这种方式简洁高效,适用于大多数需要居中对齐的场景。
1. 基本概念:justify-content 与 align-items 的作用
justify-content 控制主轴(默认为横轴)上的对齐方式,用于实现水平居中;align-items 控制交叉轴(默认为纵轴)上的对齐方式,用于实现垂直居中。
当容器设置为 flex 布局后,子元素可以在容器内自动对齐,无需关心具体尺寸。
2. 实现步骤
要让一个或多个子元素在父容器中水平垂直居中,按以下方式设置:
立即学习“前端免费学习笔记(深入)”;
- 将父容器的 display 设置为 flex
- 设置 justify-content: center 实现水平居中
- 设置 align-items: center 实现垂直居中
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 确保容器有高度 */
}
这样,所有直接子元素都会在容器中居中显示。
3. 实际应用场景
这种居中方式非常适合模态框、登录页面、卡片组件等需要内容居中的界面设计。
例如,一个简单的居中卡片:
居中内容.container { display: flex; justify-content: center; align-items: center; width: 100%; height: 100vh; background-color: #f0f0f0; }
.card { padding: 20px; background: white; border-radius: 8px; text-align: center; }
无论 .card 的宽高是多少,它都会始终位于视口正中央。
基本上就这些,不复杂但容易忽略细节,比如父容器必须有明确的高度或占据足够空间,否则 align-items 可能无法体现垂直居中效果。










