网格列值 1/1 和 1/2 之间有什么区别?

What's the difference between grid-column value 1/1 and 1/2?

在 CSS 网格中,grid-column: 1/11/2 显示相同的结果。它们之间有什么区别吗?看下面的代码。

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto;
  grid-gap: 10px;
  background-color: #2196F3;
}

.item1 {
  grid-column: 1 / 2;
}
<div class="grid-container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
  <div class="item5">5</div>
  <div class="item6">6</div>
  <div class="item7">7</div>
</div>

grid-column1 / 21 / 1 相同。有什么区别?

这是因为误解了grid-column: 1 / 2的意思。

这并不意味着跨越两列(第一列和第二列)...这意味着元素 starts at grid-line 1 结束于 grid-line 2.

Grid Track @ MDN

A grid track is the space between two grid lines. They are defined in the explicit grid by using the grid-template-columns and grid-template-rows properties or the shorthand grid or grid-template properties. Tracks are also created in the implicit grid by positioning a grid Item outside of the tracks created in the explicit grid.

所以在你的例子中,因为你有 4 列,所以有 5 explicit grid-lines(我将排除由隐式网格创建的任何 grid-lines 以避免混淆)。

由于第一列始终位于第 1 行和第 2 行之间,因此它仅跨越第一列。

  • 第 1 列:第 1 - 2 行
  • 第 2 列:第 2 - 3 行
  • 第 3 列:第 3 - 4 行
  • 第 4 列:第 4 - 5 行

grid-column: 1/1 本质上是 无效的 因此它重置为默认值,即仅跨越第一列。

A Complete Guide to Grid

网格规范中解释了差异:

8.3.1. Grid Placement Conflict Handling

If the start line is equal to the end line, remove the end line.

好的,那么当结束行被删除时会发生什么?

它计算为 auto

8.4. Placement Shorthands: the grid-column, grid-row, and grid-area properties

If two <grid-line> values are specified, the grid-row-start / grid-column-start longhand is set to the value before the slash, and the grid-row-end / grid-column-end longhand is set to the value after the slash.

When the second value is omitted, if the first value is a <custom-ident>, the grid-row-end / grid-column-end longhand is also set to that <custom-ident>; otherwise, it is set to auto.

价值auto means span 1.

一个<custom-ident> is an author-defined identifier and, in Grid, refers to named grid areas,像这样:

#grid {
 display: grid;
 grid-template-columns: [first nav-start] 150px [main-start] 1fr [last];
 grid-template-rows: [first header-start] 50px [main-start] 1fr [footer-start] 50px [last];
}

由于您的代码中没有命名网格区域,grid-column 结束行解析为 auto

因此,下面的规则都是一样的:

  • grid-column: 1 / 2
  • grid-column: 1 / 1
  • grid-column: 1 / auto
  • grid-column: 1