如何为N个元素重复Display Grid区域?多行布局问题求助
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
.cardelements 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

