CSS中的最小尺寸相等宽度包装列

发布于 2025-02-05 03:07:07 字数 800 浏览 3 评论 0原文

我的HTML中有任意数量的元素,其中包含任意内容。我希望它们在列中对齐,并且都具有相同的尺寸。如果一行溢出,我希望它们包裹,但仍然保持相同的尺寸。每列的大小应尽可能小,即最大的列确定所有列的大小。

出于这篇文章的目的,我的HTML看起来像这样:

<div class="row">
  <div>Col 1</div>
  <div>Col 2</div>
  <div>Col 3</div>
</div>

我尝试的第一件事是带有auto-fit 的CSS网格:

.row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

这有效,但是这些列的最大宽度为100px,它们不能超越超出:

https://codepen.io/diesieben07/pen/pen/pen/pen/pbxmxxjj ,根据规格,不允许使用具有最小含量的自动拟合。 如何实现所需的布局?如果在这种情况下效果更好,也欢迎使用Flex或其他布局选项。

I have an arbitrary number of elements in my HTML with arbitrary content. I want them to be aligned in columns and all have the same size. If a row overflows, I want them to wrap, but still keep the same size. The size of every column should be as small as possible, i.e. the largest column determines the size for all of them.

For the purposes of this post, my HTML looks like this:

<div class="row">
  <div>Col 1</div>
  <div>Col 2</div>
  <div>Col 3</div>
</div>

The first thing I tried was CSS Grid with auto-fit:

.row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

This works, but the columns have a maximum width of 100px that they cannot grow beyond:
https://codepen.io/diesieben07/pen/qBxMXXj

As has been discussed in many other questions, using auto-fit with min-content is not allowed per the spec.
How can I achieve the desired layout? Flex or other layout options are also welcome if they work better for this case.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剩余の解释 2025-02-12 03:07:07

要解决您的列问题,请应用以下CSS代码。希望您的问题能解决。

.row {
  width: 500px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.row > * {
  background: rebeccapurple;
  padding: 1em;
  white-space: nowrap;
}
<div class="row">
  <div>Col</div>
  <div>Col</div>
  <div>Col</div>
  <div>Col with a lot longer text</div>
  <div>Col</div>
  <div>Col</div>
  <div>Col</div>
  <div>Col</div>
</div>

To solve your column issue, apply the following css code. I hope your problem will be solved.

.row {
  width: 500px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.row > * {
  background: rebeccapurple;
  padding: 1em;
  white-space: nowrap;
}
<div class="row">
  <div>Col</div>
  <div>Col</div>
  <div>Col</div>
  <div>Col with a lot longer text</div>
  <div>Col</div>
  <div>Col</div>
  <div>Col</div>
  <div>Col</div>
</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文