如何使最后一行中的项目占用CSS网格中的剩余空间? [英] How to make the items in the last row consume remaining space in CSS Grid?

查看:72
本文介绍了如何使最后一行中的项目占用CSS网格中的剩余空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以强制网格的最后一行中的所有项目填满该行,而不管它们是多少?

Is there a way to force all the items in the last row, of a grid, to fill the row, no matter how many they are?

我不知道网格中的项目数量,因此无法直接定位它们.我尝试使用grid-auto-flow: dense,但这并没有帮助.

I do not know the number of items that will be in the grid so I cannot target them directly. I tried to use grid-auto-flow: dense, but it is not really helping.

这是我的形象化问题: :

This is my question visualized: :

div {
  margin:20px auto;
  width: 400px;
  background: #d8d8d8;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
}
span {
  height: 50px;
  background: blue;
}

<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>  
</div>
 

推荐答案

我不认为CSS Grid是您要构建的布局的最佳选择,至少如果它是动态的并且您不希望这样做,则不是这样真的不知道所有时间容器中将有多少个物品.实际上,Flexbox更适合一维布局.要使所有内容保持完全相同的大小并完全按照您的需要使用所有可用空间可能会有些困难,但是最后这种情况是Flexbox的用途.

I don't think CSS Grid is the best option for the layout you're trying to build, at least not if it's going to be dynamic and you don't really know how many items will be on the container all the time. Flexbox is actually better for one-dimensional layouts; it might be a little harder to keep everything the exact same size and using all of the available space exactly as you need it, but at the end this type of cases is what Flexbox is built for.

当然,通过在CSS上进行很少的计算,您也可以使用100%的宽度.

And of course you can make use of 100% width by using few calculations on CSS as well.

CSS Grid可能会更好地使行和列保持对齐,但这是不同的情况.

CSS Grid might be better to keep rows AND columns aligned, but this is a different case.

.container {
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
}

.flex-item {
  width: 30%;
  border: 1px solid #000;
  flex-grow: 1;
  min-height: 120px;
  box-sizing: border-box;
  margin: 0 5px 10px;
  justify-content: space-between;
  text-align: center;
}

<div class="container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
  <div class="flex-item">4</div>
  <div class="flex-item">5</div>
  <div class="flex-item">6</div>
  <div class="flex-item">7</div>
</div>

这篇关于如何使最后一行中的项目占用CSS网格中的剩余空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆