html - 为什么 grid-auto-column 没有效果?

标签 html css css-grid

我正在探索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(这是上述三个属性的简写,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;
}

三个显式行将平均分配可用空间 (1fr)。任何附加行的高度均为 200 像素。

两个显式列将平均分配可用空间。任何附加列的宽度均为 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.

关于html - 为什么 grid-auto-column 没有效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765672/

相关文章:

html - 是否有选择器以特定网格位置的元素为目标?

php - 如果循环不返回任何帖子,如何隐藏带有文本的 div?

javascript - 使用 jQuery Mobile 破坏 HTML/CSS 布局

html - 在另一个 div 内滚动 div

html - 取决于元素数量的动态网格高度

html - 为什么这个 CSS 网格以错误的像素尺寸显示?

javascript - AngularJS 提交时禁用按钮 - 错误时重新启用

javascript - 将溢出的内容从一个 div 转移到另一个 div

css - 响应式 Css float DIV 在调整窗口大小时无法正常工作

css - IE 中的空跨占用空间