如何使现有CSS Grid布局在页面中垂直水平居中
解决方案
问题出在你试图给Grid容器本身设置对齐属性,但这些属性仅作用于Grid内部的子元素。要让整个Grid布局在页面中垂直水平居中,需要给它的父容器(.main)添加布局规则,让父容器成为能居中子元素的容器。
具体修改步骤:
- 调整
body样式:移除固定height:100vh,改用min-height:100vh并清除默认外边距,避免布局溢出或留白:
body { background-color: hsl(210, 46%, 95%); font-size: 13px; font-family: "Barlow Semi Condensed", sans-serif; min-height: 100vh; margin: 0; /* 清除默认外边距 */ }
- 给
.main添加居中布局:将.main设为Flex容器,让它占满视口高度,同时垂直和水平居中内部的Grid容器,并保留底部的 attribution 位置:
.main { min-height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 20px; /* 给Grid和attribution之间留间距 */ padding: 20px; }
- 优化Grid容器的响应式宽度:给
.testimonialsmain添加最大宽度限制,避免大屏幕下布局过宽:
.testimonialsmain { display: grid; grid-template-columns: auto auto auto auto; grid-template-rows: auto auto; gap: 20px; padding: 20px; max-width: 1200px; /* 根据需求调整最大宽度 */ width: 100%; }
修改后效果说明:
.main作为Flex容器,通过justify-content: center实现垂直居中,align-items: center实现水平居中;min-height:100vh确保父容器始终占满视口高度,适配不同屏幕;- 清除
body默认外边距避免不必要的留白; - 给Grid容器设置
max-width保证大屏幕下布局不会过度拉伸,同时width:100%让它在小屏幕上自适应宽度。
完整修改后的CSS代码:
body { background-color: hsl(210, 46%, 95%); font-size: 13px; font-family: "Barlow Semi Condensed", sans-serif; min-height: 100vh; margin: 0; } .main { min-height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 20px; padding: 20px; } svg { position: absolute; justify-self: right; padding-right: 20px; } .attribution { font-size: 11px; text-align: center; } .attribution a { color: hsl(228, 45%, 44%); } .testimonialsmain { display: grid; grid-template-columns: auto auto auto auto; grid-template-rows: auto auto; gap: 20px; padding: 20px; max-width: 1200px; width: 100%; } .testimonialitem { border-radius: 5px; } .testimonialitem:nth-child(3) { grid-row: span 2; background-color: hsl(0, 0%, 100%); padding: 20px; display: grid; } .testimonialitem:nth-child(1) { grid-column: span 2; background-color: hsl(263, 55%, 52%); color: hsl(0, 0%, 81%); padding: 20px; display: grid; width: auto; } .testimonialitem:nth-child(2) { background-color: hsl(217, 19%, 35%); color: hsl(0, 0%, 81%); padding: 20px; display: grid; width: auto; } .testimonialitem:nth-child(4) { background-color: hsl(0, 0%, 100%); padding: 20px; display: grid; width: auto; } .testimonialitem:nth-child(5) { grid-column: span 2; background-color: hsl(219, 29%, 14%); color: hsl(0, 0%, 81%); padding: 20px; display: grid; width: auto; } .card { display: grid; grid-template-columns: 1fr 6fr; } .pic { border-radius: 50%; } .intro { padding-top: 10px; font-size: large; z-index: 2; } .testimonial { padding-top: 10px; }
内容的提问来源于stack exchange,提问作者Aparna
相关产品推荐
相关产品推荐

