如何让响应式正方形网格适配浏览器窗口高度?
响应式正方形网格高度限制方案
现有代码能实现窗口缩小时正方形同步缩小,但要让整个容器最大高度不超过浏览器窗口高度,且保持正方形比例。直接给.square设置min-height/max-height无效——因为网格列基于容器宽度计算,宽度不会随高度自动调整。
修改后的代码
CSS
.square-container { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); /* 行均分容器高度 */ grid-gap: 10px; max-height: 100vh; /* 容器最大高度等于视口高度 */ max-width: 100vh; /* 限制容器宽度不超过高度,避免高度溢出 */ margin: 0 auto; /* 可选:让容器居中 */ box-sizing: border-box; } .square { border: 1px solid; border-radius: 5px; aspect-ratio: 1/1; }
HTML
<div class="square-container"> <div class="square">1</div> <div class="square">2</div> <div class="square">3</div> <div class="square">4</div> <div class="square">5</div> <div class="square">6</div> <div class="square">7</div> <div class="square">8</div> <div class="square">9</div> </div>
核心逻辑
- 容器层面锁死尺寸:用
max-height:100vh把容器高度限制在视口范围内,同时max-width:100vh保证容器宽高比不超过1:1,避免因宽度过大导致高度溢出视口。 - 网格行列均分空间:添加
grid-template-rows: repeat(3,1fr)让行高度均分容器可用高度,结合列的1fr设置,使每个网格单元格的宽高基础一致。 - 强制正方形比例:
.square的aspect-ratio:1/1确保单元格始终为正方形,尺寸随容器同步缩放。
适配5x5网格的调整
只需修改grid-template-columns和grid-template-rows为repeat(5,1fr)即可,其他样式无需改动。
内容的提问来源于stack exchange,提问作者Greggy
相关产品推荐
相关产品推荐

