You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让响应式正方形网格适配浏览器窗口高度?

响应式正方形网格高度限制方案

现有代码能实现窗口缩小时正方形同步缩小,但要让整个容器最大高度不超过浏览器窗口高度,且保持正方形比例。直接给.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>

核心逻辑

  1. 容器层面锁死尺寸:用max-height:100vh把容器高度限制在视口范围内,同时max-width:100vh保证容器宽高比不超过1:1,避免因宽度过大导致高度溢出视口。
  2. 网格行列均分空间:添加grid-template-rows: repeat(3,1fr)让行高度均分容器可用高度,结合列的1fr设置,使每个网格单元格的宽高基础一致。
  3. 强制正方形比例:.square的aspect-ratio:1/1确保单元格始终为正方形,尺寸随容器同步缩放。

适配5x5网格的调整

只需修改grid-template-columns和grid-template-rows为repeat(5,1fr)即可,其他样式无需改动。

内容的提问来源于stack exchange,提问作者Greggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:07:15