CSS 网格具有可变数量的 "auto" 行,但一行应该占用"1fr"



我正在摆弄一个基于 CSS 网格的前端,在前端的不同部分需要一遍又一遍地使用以下行为:

  1. 具有可变行数的网格。
  2. 每一行都应该有一个可变的大小(自动就可以了)。
  3. 最后一行应始终占用所有剩余空间。

因此,在我碰巧需要五行的情况下,这可以解决问题:

.myGridForFiveRows
{
display: grid;
grid-template-rows: auto auto auto auto 1fr;
}

但是,我真的很想要一个样式表,它可以为任何给定数量的行产生正确的行为。我想也许我可以以某种方式使用repeat()来做到这一点?

https://developer.mozilla.org/en-US/docs/Web/CSS/repeat

.myGrid
{
display: grid;
grid-template-rows: repeat(auto-fit, auto) 1fr;
}

我一直在玩repeat(auto-fit, auto)repeat(auto-fill, auto)的变体,不幸的是,它们不是合法的CSS,而repeat(4, auto)repeat(auto-fill, 30px)是。

知道吗?这不是我无法规避的事情,但碰巧"显示 n 个大小合适的行,然后让最后一个元素占用所有剩余空间"基本上是我规范中所有元素的默认行为......

考虑您的三个要求:

  1. 具有可变行数的网格。
  2. 每一行都应该有一个可变的大小(自动就可以了)。
  3. 最后一行应始终占用所有剩余空间。

弹性框非常适合这项工作。事实上,它可能非常适合(取决于您的其他要求)。我在下面提供了一个代码示例。

但是,如果网格布局是你想要的,那么我认为你会失望的。我不相信1 级可以胜任这项工作。

您可以获得的最接近的是:

grid-template-rows: repeat(auto-fit, minmax(auto, 1px)) 1fr;

但它不起作用,因为当前的网格规范不支持此语法。

repeat(auto-fit, auto) 1fr

这是您尝试过的代码。它无效,因为autofr不能与auto-fit一起使用。

7.2.2.1. 语法repeat()

自动重复(auto-fillauto-fit)不能组合 具有固有灵活的尺寸。

  • 内在大小函数是min-contentmax-contentautofit-content()

  • 灵活的尺寸调整功能是<flex>(fr)。

您可以通过这样的方式来绕过auto限制:

repeat(auto-fit, minmax(auto, 1px)) 1fr

minmax(min,max)

定义大于或等于最小且小于或的大小范围 等于最大值

如果最大值<分钟>,则忽略最大值minmax(min,max)被视为最小值。

<flex>值设置轨道的挠度系数最大值;该值至少无效。

这可以正确调整行的大小,无论容器具有默认的auto高度还是定义了height/min-height。 演示

但它仍然不能解决最后一行问题,因为1fr仍然无效,并导致整个规则失败。

像这样的东西是有效的:

repeat(auto-fit, minmax(auto, 1px)) 10em

但是auto-fit没有按预期工作:10em应用于第二行。

演示如果容器定义了heightmin-height,则规则不会按预期工作。 演示


即使CSS Grid Layout现在广泛使用,在某些情况下,Flexbox仍然是更好的选择。

这通过干净简单的代码涵盖了您的所有要求:

article {
display: flex;
flex-direction: column;
height: 100vh;
}
section:last-child {
flex-grow: 1;
}
section {
/* flex-basis: auto <-- this is a default setting */
margin-bottom: 10px;
background-color: lightgreen;
}
body {
margin: 0;
}
<article>
<section>text text text</section>
<section>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
text text text text text text text text text text </section>
<section>text text text text text text text text text text text text text text text text text text text text text text text text text text text</section>
<section>text text text text text text text text text text text text text text text text text text text text text text text text text text text</section>
<section>text text text text text text text text text text text text text text text text text text text text text text text text text text text</section>
</article>

这有点麻烦,但你可以输入一个非常大的数字来重复你永远不会越过。 例如,您可以对网格模板行执行此操作:

网格模板行:重复(100000000,自动)1fr;

我有同样的问题,这对我有用。

最新更新