如何在CSS Grid中让指定孙元素跨100%宽度(父容器3等分)
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
.containerinto 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

