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

如何实现两个Grid网格相邻排列,多余矩形自动换行展示

错误点修正

  • 样式属性拼写错误:grid-template-colums 应为 grid-template-columns,属性值不需要加引号
  • 布局规则逻辑错误:flex/grid的排列规则需要定义在父容器上,给子元素.square、.rectangle单独加列规则不生效
  • 未配置换行规则,元素宽度超出容器时不会自动折行

完整实现代码

flex方案(兼容性更好)

<div class="outer">
  <div class="square"></div>
  <div class="rectangles">
    <div class="rectangle">矩形1</div>
    <div class="rectangle">矩形2</div>
    <div class="rectangle">矩形3</div>
    <div class="rectangle">矩形4</div>
  </div>
</div>
.outer {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.square {
  width: 200px;
  height: 200px;
  background: #ccc;
  flex-shrink: 0;
}

.rectangles {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  flex: 1;
  min-width: calc(200px * 2 + 16px);
}

.rectangle {
  width: calc((100% - 16px) / 2);
  height: 200px;
  background: #2e86de;
}

grid方案(代码更简洁)

<div class="outer">
  <div class="square"></div>
  <div class="rectangle">矩形1</div>
  <div class="rectangle">矩形2</div>
  <div class="rectangle">矩形3</div>
  <div class="rectangle">矩形4</div>
</div>
.outer {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.square {
  height: 200px;
  background: #ccc;
}

.rectangle {
  height: 200px;
  background: #2e86de;
}

上述代码中200px为单个元素的基准宽度,16px为元素间隙,可根据实际需求调整数值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:15:08