如何使用具有最小尺寸的项目显示相同数量的项目

发布于 2025-01-30 02:34:29 字数 1231 浏览 2 评论 0原文

我想知道是否有一种方法可以始终使用网格模板显示每个行的相同数量的项目。网格似乎是最明显的选择,因为我想在水平和垂直方向上放置物品。

我已经习惯了重复(自动填充,...)这样,

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
}

但这只会推动下一行所需的最小元素,以使第一行的元素在第一行中具有最小尺寸10em。

我想要的是,考虑到6个元素的列表,如果该行不能包含其最小尺寸的整个6个元素,则将2行构成3个元素。同样,如果没有足够的空间,请用2个元素等3行,

这可以用媒体试价完成(因为我知道总会有6个元素)

.grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(5em, 1fr));
  gap: 3px;
}

@media screen and (min-width: 20em) {
  .grid {
    grid-template-columns: repeat(3, minmax(5em, 1fr));
  }
}

@media screen and (min-width: 40em) {
  .grid {
    grid-template-columns: repeat(6, minmax(5em, 1fr));
  }
}

.grid > div {
  border: 1px solid black;
  height: 2em;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>

但这看起来不是很干净,我想知道该用例中是否有一个内置解决方案(或者是否在网格外有解决方案)。

I wanted to know if there is a way to always display the same number of items for each rows using grid template. Grid seems the most obvious choice since I want to have items behind aligned horizontally and vertically.

I'm already used to repeat(auto-fill, ...) like this

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
}

But this will only push the minimum number of elements needed to the next line to makes elements on the first line with minimum size of 10em.

What I would like is, considering a list of 6 elements, if the line cannot contain the whole 6 elements with their minimum size, make 2 lines of 3 elements. Again, if there is not enough space, make 3 lines with 2 elements etc.

This could be done with media-query (since I know there will always be 6 elements)

.grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(5em, 1fr));
  gap: 3px;
}

@media screen and (min-width: 20em) {
  .grid {
    grid-template-columns: repeat(3, minmax(5em, 1fr));
  }
}

@media screen and (min-width: 40em) {
  .grid {
    grid-template-columns: repeat(6, minmax(5em, 1fr));
  }
}

.grid > div {
  border: 1px solid black;
  height: 2em;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>

But this doesn't look very clean, and I would like to know if there is a built-in solution in grid template for this use case (or if there is a solution outside of grid).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文