为什么 `minmax` 总是使用最大值 space?

Why does `minmax` always use maximum space?

正如您在这个简单示例中所看到的,每个网格单元始终使用最大可能的数量 space。为什么会发生这种情况,我如何才能说服网格尽可能少地使用 space?

.testgrid {
  display: grid;
  grid-template-columns: 20% minmax(20%, 80%);
  grid-auto-rows: minmax(1.5em, 4.5em);
}

.testgrid .item {
  background-color: #AF6;
  margin: 1px;
  overflow: hidden;
}
<div class="testgrid">
  <div class="item">Cell 1</div>
  <div class="item">Cell 2</div>
  <div class="item">Cell 3 (uses too much space, so really it ought to be clipped)</div>
  <div class="item">Cell 4</div>
  <div class="item">Cell 5</div>
  <div class="item">Cell 6 (more text here, could push the column wider)</div>
</div>

它是 css3 函数,取决于您的元素大小和屏幕大小。

当你使用minmax时,css网格可以使用内容敏感的大小调整,但显然,只要你添加minmax,网格忽略内容并在不同的单元格之间平分 space。如果可能,minmax 也更愿意浪费 space;如果容器受到限制(例如,通过固定的 heightwidth。)

,它只会使用少于最大值

因此,如果您想要内容敏感的大小调整,请避免 minmax。事实上,内容敏感的大小调整似乎只支持 auto(不,你不能写类似 calc(auto+2fr) 的东西来获得更智能的免费分发 space。)

通过使用 auto 作为行高并将最小值和最大值设置为 items[=45= 的属性,可以实现具有最小和最大行高的预期效果] 而是:

.testgrid {
  display: grid;
  grid-template-columns: 20% auto 1fr;
  grid-auto-rows: auto;
  max-width: 600px;
}

.testgrid .item {
  background-color: #AF6;
  margin: 1px;
  overflow: hidden;
  min-height: 1.5em;
  max-height: 4.5em;
}
<div class="testgrid">
  <div class="item">Cell 1</div>
  <div class="item">Cell 2</div>
  <div></div>
  <div class="item">Cell 3 (uses too much space, so really it ought to be clipped)</div>
  <div class="item">Cell 4</div>
  <div></div>
  <div class="item">Cell 5</div>
  <div class="item">Cell 6 (more text here, could push the column wider)</div>
  <div></div>
</div>

我找不到使用小于最大列宽的简单方法(这很奇怪,因为 HTML tables 默认情况下是这样的,所以如果 css 网格系统,理想情况下会使 table 布局过时,但不提供用于此目的的功能。)justify-items: start(或 .item 中的 justify-self: start)导致单个单元格彼此独立地收缩,但如果您希望列中的所有单元格具有相同的宽度,这是不可取的。

作为解决方法,我添加了一个虚拟的第三列来占据未使用的 space。不幸的是,这不仅仅是 CSS; HTML 必须知道虚拟列。为了使其正常工作,虚拟列需要使用 fr 单位,而所有其他列必须是固定宽度或 auto.

我认为你需要 max-content,这应该有效:

.testgrid {
  display: grid;
  grid-template-columns: 20% minmax(20%, max-content);
  grid-auto-rows: minmax(1.5em, 4.5em);
}