为什么 CSS 网格的自动填充属性在列方向上不起作用



我正在练习用行自动填充属性,但是,它没有做我想要的。我想创建高度minmax(140px, 200px)的行,但得到一行高度为 200px,其余为 18px。为什么会这样?

body,
html {
height: 100%;
margin: 0;
}
.wrapper {
display: grid;
grid-template-rows: repeat(auto-fill, minmax(140px, 200px));
}
.wrapper>div:nth-child(odd) {
background-color: red;
}
<div class="wrapper">
<div class="one"> 1 </div>
<div class="one"> 1 </div>
<div class="one"> 1 </div>
<div class="one"> 1 </div>
<div class="one"> 1 </div>
</div>

要在垂直方向上包装网格,您必须做更多的事情:

  • 网格容器指定一个height,以便网格项知道何时换行,

  • 还要指定grid-auto-flow: column(覆盖默认grid-auto-flow: row)

请参阅下面的演示(已设置height: 100%以进行说明):

body,
html {
height: 100%;
margin: 0;
}
.wrapper {
display: grid;
grid-template-rows: repeat(auto-fill, minmax(140px, 200px));
grid-auto-flow: column; /* added */
height: 100%; /* adjust this*/
}
.wrapper>div:nth-child(odd) {
background-color: red;
}
<div class="wrapper">
<div class="one"> 1 </div>
<div class="one"> 2 </div>
<div class="one"> 3 </div>
<div class="one"> 4 </div>
<div class="one"> 5 </div>
</div>


为什么要指定高度?

因为auto-fillauto-fit在该轴上需要一个确定的维度:

7.2.3.2. Repeat-to-fill: auto-fill and auto-fit repetitions

当自动填充作为重复编号给出时,如果网格 容器在相关轴上具有确定的大小或最大大小,则 重复次数是可能的最大正整数 不会导致网格溢出其网格的内容框 容器(将每个轨道视为其最大轨道大小调整函数,如果 这是确定的或作为其最小轨道大小函数,否则, 并考虑到差距);如果任何重复次数会 溢出,然后重复 1 次。否则,如果网格容器具有 相关轴上的确定最小尺寸,重复次数为 满足该最小值的最小可能正整数 要求。否则,指定的曲目列表仅重复一次。


行方向自动填充更简单

请注意,在这里,您不需要指定宽度,因为display: grid块元素,块元素具有视口的宽度。您可以在此处使用grid-template-columns: repeat(auto-fill, minmax(140px, 200px))

body,
html {
height: 100%;
margin: 0;
}
.wrapper {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 200px));
/*grid-auto-flow: row; --> default (so not needed) */
}
.wrapper>div:nth-child(odd) {
background-color: red;
}
<div class="wrapper">
<div class="one"> 1 </div>
<div class="one"> 2 </div>
<div class="one"> 3 </div>
<div class="one"> 4 </div>
<div class="one"> 5 </div>
</div>


为什么grid-auto-flow: column

请参阅其定义的相关摘录 - 此属性控制网格项在网格容器中的流动方式(如果未显式放置):

grid-auto-flow

网格自动流 CSS 属性控制自动放置的方式 算法有效,准确指定自动放置的项目如何流动 进入网格。

grid-auto-flow的默认值为row这就是为什么您需要覆盖它以column

row

自动放置算法通过依次填充每一行来放置项目, 根据需要添加新行。如果未提供行或列, 行是假定的。

最新更新