为什么CSS Grid的自动填充属性不在列方向上工作

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

我正在用行练习自动填充属性,但是,它没有按照我的意愿行事。我想创建高度为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>
html css css3 vertical-alignment css-grid
1个回答
3
投票

要在垂直方向上包裹网格,您还需要做更多的事情:

  • 为网格容器指定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次。否则,如果网格容器在相关轴中具有确定的最小尺寸,则重复次数是满足该最小要求的最小可能正整数。否则,指定的曲目列表仅重复一次。


Auto-fill in row direction is simpler

请注意,在这里,您不需要指定宽度,因为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

grid-auto-flow CSS属性控制自动放置算法的工作方式,准确指定自动放置的项目如何流入网格。

grid-auto-flow的默认值是row,这就是你需要将它覆盖到column的原因:

row

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

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