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

如何为N个元素重复Display Grid区域?多行布局问题求助

Fixing Multi-Row Grid Layout for N Repeating Cards

Got it, let's tackle this grid layout problem where you want multiple .card elements to fill the left "list" area in a multi-row setup, while keeping the banner fixed on the right.

The Issue with Your Original Code

Your current CSS uses grid-template-areas: "list advertisment" which only defines a single row. When you set grid-area: list on every .card, all those cards end up stacked on top of each other in the same grid cell—they don't automatically flow into new rows. That's why you weren't seeing the multi-row layout you wanted.

Solution: Flexible Grid with Auto-Rows and Full-Height Banner

Here's a revised approach that lets N number of cards fill the left area in rows, while the banner stays anchored to the right and spans all rows:

HTML (unchanged)

<div class="list-view">
  <div class="card">lorem</div>
  <div class="card">ipsum</div>
  <div class="card">dolor</div>
  <div class="card">sit</div>
  <div class="card">lorem</div>
  <div class="card baner">banner</div>
</div>

Revised CSS

.list-view {
  display: grid;
  border: 1px solid red;
  grid-template-columns: auto 240px; /* Keep the two-column structure */
  grid-auto-rows: 100px; /* Auto-create rows matching your card height */
  gap: 4px; /* Optional: add spacing between cards for better readability */
}

.card {
  background: #ccc;
  border: 1px solid green;
  /* No grid-area needed—cards automatically fill the first column's rows */
}

.card.baner {
  background: yellow;
  grid-row: 1 / -1; /* Make the banner span from the first to last row */
}

How This Works

  • grid-auto-rows: 100px: Tells the grid to automatically create new 100px-tall rows whenever there are more cards than existing rows, perfectly matching your card height.
  • grid-row: 1 / -1: Makes the banner occupy every row in the second column, so it stays full-height no matter how many cards are on the left.
  • Any extra .card elements you add will automatically flow into new rows in the first column—no extra code needed to handle N elements.

Alternative: Using Grid Template Areas (Less Flexible)

If you prefer sticking with grid-template-areas, you'd need to predefine rows, which isn't ideal for unknown numbers of cards. The method above is far better for dynamic, N-element layouts since it adapts automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:39:17