为什么 grid-auto-columns 没有效果?

Why is grid-auto-columns having no effect?

我正在探索 CSS Grid Layout,这是我不明白的地方。我已经将 grid-auto-columnsgrid-template-columns 一起使用,但它不会影响任何东西。

我尝试在 grid-auto-columns 中设置各种值,但它没有任何影响。

为什么不呢?

* {
  box-sizing: border-box;
}

.wrapper {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-auto-columns: 50px;
  grid-auto-rows: 200px;
  grid-gap: 20px;
}

.wrapper>div {
  border: 2px solid rgb(233, 171, 88);
  border-radius: 5px;
  background-color: rgba(233, 171, 88, .5);
  padding: 1em;
  color: #d9480f;
}
<div class="wrapper">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>

简答

grid-auto-columns 没有效果的原因是 隐式 网格中缺少列。


说明

在CSS网格布局中,有两种类型的网格:显式隐式

显式网格 是您显式定义的网格。当您使用以下属性时,您创建了一个显式网格:

  • grid-template-rows
  • grid-template-columns
  • grid-template-areas
  • grid(也就是上面三个属性的shorthand,among others

但是,您不需要将网格项目保留在显式网格中。您基本上可以在任何您想要的地方放置项目和创建网格区域,甚至可以在显式网格之外。这就是隐式网格的用武之地。

隐式网格 由自动生成的行和列创建,以容纳位于显式网格之外的网格项目。

grid-template-columnsgrid-template-rows 大小显式轨道,grid-auto-columnsgrid-auto-rows 大小隐式轨道。

查看您的代码,显式网格中有两列和三行。

.wrapper {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-auto-columns: 50px;
  grid-auto-rows: 200px;
  grid-gap: 20px;
}

三个显式行将平均分配免费 space (1fr)。任何额外的行都将具有 200 像素的高度。

两个显式列将平均分配免费 space。任何额外的列都将具有 50 像素的宽度。

但是在您的代码中,显式网格之外没有任何列;只有两列。所以grid-auto-columns没有效果。

规范定义这些网格类型的方式如下:

7.1. The Explicit Grid

The three properties grid-template-rows, grid-template-columns, and grid-template-areas together define the explicit grid of a grid container.

The grid property is a shorthand that can be used to set all three at the same time.

The final grid may end up larger due to grid items placed outside the explicit grid; in this case implicit tracks will be created, these implicit tracks will be sized by the grid-auto-rows and grid-auto-columns properties.


7.5. The Implicit Grid

The grid-template-rows, grid-template-columns, and grid-template-areas properties define a fixed number of tracks that form the explicit grid.

When grid items are positioned outside of these bounds, the grid container generates implicit grid tracks by adding implicit grid lines to the grid.

These lines together with the explicit grid form the implicit grid.

The grid-auto-rows and grid-auto-columns properties size these implicit grid tracks.