.container { display: grid; grid-template-columns: repeat(auto-fill,100px); grid-gap: 3px; border: 1px solid green; } .item { border: 1px solid red; height: 50px; }
<div class="container"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div>
如何将红色物品盒拉伸一点,以便它们填满绿色容器盒的整个宽度?
它们应该都是相同的宽度,并且大于100px.
最后一行应该像现在一样左对齐.
解决方法
您只需要将一个分数单位添加到grid-template-columns规则中.
grid-template-columns: repeat(auto-fill,minmax(100px,1fr));
此规则会创建适合容器的列数.
每列的最小宽度为100px.
最大宽度为1fr,这意味着该列将消耗该行上的任何可用空间.
现在正在使用容器中的所有水平空间.
.container { display: grid; grid-template-columns: repeat(auto-fill,1fr)); grid-auto-rows: 50px; grid-gap: 3px; border: 1px solid green; } .item { border: 1px solid red; }
<div class="container"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div>
这些帖子更详细地解释了上面的解决方案:
> Equal width flex items even after they wrap
> The difference between percentage and fr units in CSS Grid Layout