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

如何让Grid缩小适配父级Flexbox避免溢出(保持1:1比例)

解决方案

要让Grid自适应父容器可用高度且保持单元格1:1宽高比,核心是让Grid整体保持与行列数匹配的宽高比,再利用容器的弹性布局限制其最大尺寸。以下是修改后的代码:

HTML(无需改动)

<div class="container">
  <header>header</header>
  <div class="game">
    <div class="puzzle">
      <div></div>     
      <div></div>     
      <div></div>     
      <div></div>      
      <div></div>     
      <div></div> 
      <div></div>      
      <div></div>     
      <div></div>    
      <div></div>      
      <div></div>     
      <div></div>                
    </div>  
  </div>
  <footer>footer</footer>
</div>

修改后的CSS

html {
  display: flex;
  height: 100vh;
  margin: 0;
}

body {
  display: flex;
  flex: 1;
  justify-content: center;
  margin: 0;
}

.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 425px;  
  height: 100%; /* 确保容器占满视口高度 */
  background: grey;
}

header, footer {
  /* 让头部和脚部高度由内容决定,不挤压中间区域 */
  flex-shrink: 0;
}

.game {
  flex: 1; /* 占据header和footer之外的所有可用空间 */
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 1rem; /* 可选:防止Grid贴边 */
}

.puzzle {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  aspect-ratio: 3/4; /* 列数/行数,保持Grid整体宽高比与行列数匹配 */
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.puzzle > * {
  border: 1px solid black;
  aspect-ratio: 1/1;
}

关键说明

  1. 容器高度控制:给.container设置height: 100%,确保它完全填充视口高度;同时给header和footer加flex-shrink: 0,避免它们被中间区域挤压变形。
  2. 中间区域弹性分配:.game设置flex: 1,自动占据头部和脚部之外的剩余空间,并用flex布局让Grid居中显示。
  3. Grid自适应核心:.puzzle设置aspect-ratio: 3/4(对应3列4行的布局),这样Grid整体的宽高比固定为列数:行数。结合max-width: 100%和max-height: 100%,Grid会自动缩放到不超出.game的可用空间,同时保持单元格1:1的宽高比(因为Grid的列是等分宽度,行是等分高度,而整体宽高比为3:4,所以每个单元格的宽=Grid宽度/3,高=Grid高度/4,两者相等)。

这种方式完全不需要滚动条或溢出隐藏,且能适配任意屏幕高度,同时支持动态生成的行列数(只需修改aspect-ratio为对应列数/行数即可)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:40:37