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

如何在CSS Grid中让指定孙元素跨100%宽度(父容器3等分)

Can I achieve this layout with CSS Grid?

Absolutely! CSS Grid is ideal for this layout requirement, and your existing code already lays the groundwork for it. Let’s break this down:

Your Current Setup Explained

Your .container is correctly configured as a 3-column grid with grid-template-columns: repeat(3, 1fr)—this rule automatically splits the container’s width into 3 equal, flexible columns. Each direct child <div> of .container automatically occupies one grid column, and the nested .child_01/.child_02 elements are centered within their parent columns using margin: 1rem auto—this already gives you the core 3-column layout you’re aiming for.

Optimized Code Example

To make the layout cleaner and more polished, you can add a gap to the grid to create spacing between columns, and remove the redundant width: 100% on .container > div (Grid child elements automatically fill their grid cell by default):

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem; /* Adds space between grid columns */
}

.container > div {
  background-color: #4834d4;
}

.container > div .child_01 {
  background-color: #f9ca24;
  width: 80%;
  height: 50px;
  margin: 1rem auto;
}

.container > div .child_02 {
  background-color: #eb4d4b;
  width: 80%;
  height: 50px;
  margin: 1rem auto;
}
<div class="container">
  <div>
    <div class="child_01"></div>
    <div class="child_02"></div>
  </div>
  <div>
    <div class="child_01"></div>
    <div class="child_02"></div>
  </div>
  <div>
    <div class="child_01"></div>
    <div class="child_02"></div>
  </div>
</div>

Why This Works

  • repeat(3, 1fr) ensures each column takes an equal share of the available space, adapting smoothly to the container’s width.
  • Grid automatically places each direct child of .container into a separate grid column—no extra positioning rules are needed.
  • The nested child elements stay centered within their column thanks to the auto margins, maintaining the visual structure you want.

So yes, CSS Grid is completely capable of delivering this layout, and your initial code was already most of the way there!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:57:56