使用CSS Grid垂直居中可通过align-items和justify-items实现;推荐用place-items: center简写或对单个子元素设置align-self与justify-self,结合min-height: 100vh避免溢出。

要使用 CSS Grid 实现垂直居中布局,最直接的方法是利用
align-items
justify-items
align-self
justify-self
如果你希望容器内的所有子元素都垂直水平居中,可以这样设置:
.container {
display: grid;
height: 100vh; /* 占满视口高度 */
align-items: center; /* 垂直居中 */
justify-items: center; /* 水平居中 */
}
这个方法适用于只有一个子元素的情况,或你希望所有子项都居中对齐。
当你需要更精确地控制布局时,可以用
grid-template-areas
place-items
立即学习“前端免费学习笔记(深入)”;
.container {
display: grid;
height: 100vh;
place-items: center; /* 同时设置 align-items 和 justify-items */
}
place-items: center
align-items
justify-items
如果容器中有多个元素,但只想让其中一个垂直水平居中,可以针对该子元素单独设置:
.container {
display: grid;
height: 100vh;
}
<p>.centered {
justify-self: center; /<em> 水平居中 </em>/
align-self: center; /<em> 垂直居中 </em>/
}</p>这种方法不会影响其他子元素的布局,灵活性更高。
有时内容较少,但仍需在视口中居中,可结合
min-height
height: 100vh
.container {
display: grid;
min-height: 100vh;
align-items: center;
justify-items: center;
}
使用
min-height
height
基本上就这些。CSS Grid 提供了非常简洁的方式来实现垂直居中,关键是理解
align-items
justify-items
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号