CSS 网格重复(自动调整)会中断。有办法预防吗?

问题描述 投票:0回答:1

auto-fill
auto-fit
之间的区别在于后者折叠了空列。

但是在添加一个跨越所有列的项目之后,

auto-fit
会中断并开始表现得像
auto-fill
。无论如何,我在规范中找不到这种行为。我补充说这只是糟糕的实施。

有办法预防吗?

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

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

div > div {
  aspect-ratio: 1;
  background-color: gold;
  border: 1px solid black;
}

h2 {
  grid-column: 1 / -1;
}
<h1>repeat(auto-fit)</h1>
<div class="auto-fit">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<h1>repeat(auto-fill)</h1>
<div class="auto-fill">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<h1>repeat(auto-fit) with</h1>
<div class="auto-fit">
  <h2>element spanning all columns</h2>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

css css-grid
1个回答
0
投票

根据 CSS 网格规范,您在添加跨越元素时通过自动调整折叠空列观察到的行为确实是预期的。使用自动调整时,网格将创建尽可能多的轨道,同时保持定义的最小和最大尺寸。添加跨越元素后,它会有效地占用一个或多个轨道,从而导致网格通过折叠空列进行调整。

如果您想防止这种行为并保持网格轨道一致,即使添加了跨越元素,您可以对 grid-template-columns 属性使用 auto-fill、minmax 和 max-content 的组合。

.auto-fill {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, max-content));
}
<h1>repeat(auto-fill) with</h1>
<div class="auto-fill">
  <h2>element spanning all columns</h2>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

通过使用 max-content,您可以确保每个轨道的宽度足以容纳其中最宽的内容。这可以防止添加跨越元素时空列的折叠。

© www.soinside.com 2019 - 2024. All rights reserved.