首页 > 解决方案 > 为什么`minmax`总是使用最大空间?

问题描述

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

.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>

标签: cssgridminmax

解决方案


当您使用minmax时,css 网格可以使用内容敏感的大小,但显然,一旦您添加minmax,网格就会忽略内容并在不同单元格之间平均划分空间。minmax如果可能,也更喜欢浪费空间;height如果容器受到约束(例如,通过固定或width.),它只会使用小于最大值

minmax因此,如果您想要内容敏感的大小,请避免。事实上,内容敏感的大小似乎只支持auto(而且不,你不能编写类似的东西calc(auto+2fr)来获得更智能的可用空间分配。)

可以通过使用auto作为行高并将最小值和最大值设置为项目的属性来实现具有最小和最大行高的预期效果:

.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 表格的行为方式是这样的,所以如果 css 网格系统(理想情况下会使表格布局过时)不t 为此目的提供功能。)justify-items: start(或justify-self: startin .item)导致单个单元格彼此独立收缩,但如果您希望列中的所有单元格具有相同的宽度,则这是不可取的。

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


推荐阅读