具有可变数量的"自动"行的CSS网格,但是一行应该采用"1fr"

Sas*_*cha 7 html css css3 css-grid

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

  1. 具有可变行数的网格.
  2. 每一行都应该有一个可变的大小(auto会这样做).
  3. 最后一行应始终占用所有剩余空间.

因此,在我碰巧需要五行的情况下,这就是诀窍:

.myGridForFiveRows
{
    display: grid;
    grid-template-rows: auto auto auto auto 1fr;
}
Run Code Online (Sandbox Code Playgroud)

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

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

.myGrid
{
    display: grid;
    grid-template-rows: repeat(auto-fit, auto) 1fr;
}
Run Code Online (Sandbox Code Playgroud)

我一直在玩弄的变种repeat(auto-fit, auto)repeat(auto-fill, auto),不幸的是不合法的CSS,而repeat(4, auto)repeat(auto-fill, 30px)有.

任何的想法?这不是我无法规避的事情,但恰好"显示n个正确大小的行,然后让最后一个元素占用所有剩余空间"基本上是我的规范中所有元素的默认行为...

Mic*_*l_B 8

考虑到您的三个要求:

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

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

但是如果 Grid Layout 是你想要的,那么我想你会失望的。我不相信Level 1可以胜任这项工作。

你能得到的最接近的是:

grid-template-rows: repeat(auto-fit, minmax(auto, 1px)) 1fr;
Run Code Online (Sandbox Code Playgroud)

但它不会工作,因为当前的网格规范不支持这种语法。

repeat(auto-fit, auto) 1fr

这是您尝试的代码。它无效,因为auto并且fr不能与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)

定义大于或等于min且小于或等于max的大小范围。

如果max < min,则max被忽略并被minmax(min,max)视为min

作为最大值,一个<flex>值设置轨道的弹性系数;它至少是无效的。

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

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

这样的事情是有效的:

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

但是auto-fit不像您期望的那样工作:10em应用于第二行。演示

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


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

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

grid-template-rows: repeat(auto-fit, minmax(auto, 1px)) 1fr;
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)