HTML和CSS Grid布局异常:网格区块堆叠显示问题求助
解决Grid布局区块不显示的问题
问题根源
你遇到的问题核心出在两点:
- 高度传递失效:
main和article的height:100%未生效,因为父元素(html、body)既没设置明确高度,也没通过弹性布局让main撑满剩余空间,导致article实际高度为0,仅顶部区块的边框露出一条白线。 - Grid结构未定义:仅给
article添加display:grid,但未指定行的数量和尺寸,所有子元素默认挤在同一行,无法呈现多行结构。
修复步骤
1. 修复父元素高度传递
修改body, html的CSS,让它们占满视口高度,并将body设为弹性布局容器,让main自动填充导航栏下方的剩余空间:
body,html{ overflow-x: hidden; font-family: "Poppins", sans-serif; height: 100%; /* 让html和body占满视口高度 */ display: flex; /* 启用弹性布局 */ flex-direction: column; /* 垂直排列子元素 */ }
2. 定义Grid的行结构
给article添加行模板,明确创建4个等高的行,可额外添加间距方便区分区块:
main > article { display: grid; height: 100%; grid-template-rows: repeat(4, 1fr); /* 创建4个等比例高度的行 */ gap: 1rem; /* 可选:给行之间添加间距 */ }
3. 简化子元素样式(可选)
.article-section的height:100%可以移除,因为Grid子元素默认会自动填充所在单元格的高度:
main > article > .article-section{ border: 0.1px solid white; background-color: white; /* 移除height:100% */ }
修复后的完整CSS代码
*{ margin: 0; padding: 0; box-sizing: border-box; } body,html{ overflow-x: hidden; font-family: "Poppins", sans-serif; height: 100%; display: flex; flex-direction: column; } html{ background-color: black; } .webgl{ position: absolute; top: 0; left: 0; z-index: 1; } nav{ color: white; z-index: 2; position: relative; padding: 4rem 4rem; display: flex; justify-content: space-between; } nav a{ text-decoration: none; color: white; font-weight: bold; } nav ul{ list-style: none; display: flex; gap: 2rem; } main { flex-grow: 1; } main > article { display: grid; height: 100%; grid-template-rows: repeat(4, 1fr); gap: 1rem; } main > article > .article-section{ border: 0.1px solid white; background-color: white; }
额外说明
如果你的6个.article-section需要在4行里按多列排列(比如每行2个),可以添加grid-template-columns: repeat(2, 1fr);到main > article的样式中,自动适配所有区块的布局。
内容的提问来源于stack exchange,提问作者Michaelangelo07
相关产品推荐
相关产品推荐

