使用 justify-content 和 align-items 可实现 Flexbox 水平垂直居中:justify-content 控制主轴(水平)对齐,设为 center 实现水平居中;align-items 控制交叉轴(垂直)对齐,设为 center 实现垂直居中;两者结合可使元素在容器内完全居中,需确保容器有明确高度,常用于登录页、卡片布局等场景。

在使用 Flexbox 布局时,水平居中和垂直居中是常见的布局需求。通过 justify-content 和 align-items 两个属性,可以轻松实现内容的居中对齐。下面结合实战说明如何正确使用它们。
justify-content 用于设置 flex 容器内子元素在主轴(main axis)上的对齐方式。默认主轴是水平方向(row),所以它常用来实现水平居中。
要实现水平居中,将容器的 justify-content 设置为 center:
.container {
display: flex;
justify-content: center; /* 水平居中 */
}
align-items 用于设置子元素在交叉轴(cross axis)上的对齐方式。当主轴是水平方向时,交叉轴就是垂直方向,因此它控制垂直居中。
立即学习“前端免费学习笔记(深入)”;
常用值有:要实现垂直居中,设置 align-items: center:
.container {
display: flex;
align-items: center; /* 垂直居中 */
}
如果想让一个或多个子元素在容器中完全居中(既水平又垂直),只需同时使用两个属性:
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 确保容器有高度,否则看不出垂直效果 */
}
这样,所有子元素会在容器中居中显示,非常适合做登录页、弹窗或欢迎界面的布局。
假设我们要创建一个页面,中间显示一张卡片,并水平垂直居中:
<div class="card-container"> <div class="card">欢迎使用 Flex 居中</div> </div>
CSS 样式如下:
.card-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
<p>.card {
width: 300px;
height: 200px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: flex;
justify-content: center;
align-items: center;
font-size: 18px;
}</p>这个例子中,外层容器使用 Flex 居中卡片,卡片内部也居中文本,整体视觉非常平衡。
基本上就这些。掌握 justify-content 和 align-items 的作用方向,就能灵活应对大多数居中布局场景。不复杂但容易忽略的是容器必须有明确尺寸(尤其是高度),否则 align-items: center 可能无效。
以上就是如何使用CSS实现Flex水平居中_align-items与justify-content实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号