为什么我将网格行设置为跨度2时却跨越了1行?

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

我在以下代码中有一个与网格行和跨度有关的问题:

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

.item {
  padding: 3rem;
  border: 1px solid #ccc;
  background: #f4f4f4;
  font-size: 1.3rem;
  font-weight: bold;
  text-align: center;
}

.item:first-child {
  grid-column: 1 / span 3;
  grid-row: 1 / span 2;
  background: blueviolet;
}

.item:nth-child(9) {
  grid-column: 2 / span 3;
  grid-row: 2 / span 2;
  background: red;
}
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
  <div class="item">Item 4</div>
  <div class="item">Item 5</div>
  <div class="item">Item 6</div>
  <div class="item">Item 7</div>
  <div class="item">Item 8</div>
  <div class="item">Item 9</div>
  <div class="item">Item 10</div>
  <div class="item">Item 11</div>
  <div class="item">Item 12</div>
  <div class="item">Item 13</div>
  <div class="item">Item 14</div>
  <div class="item">Item 15</div>
</div>

这是输出?:

enter image description here

正如我们在输出屏幕截图中所看到的,Item1仅跨越1行,而item 9仅跨越1行,但是在CSS样式中,我为item1和item9提供了2的行跨度。有人可以解释原因吗?

html css css-grid
1个回答
2
投票

在您的.grid样式块中,您需要包括一个明确的grid-template-rows样式声明。

一旦.grid 明确地包含多行,您对Item 1Item 9的样式将起作用。

例如

grid-template-rows: 1fr 1fr;

或,如@ Paulie_D所建议:

grid-template-rows: minmax(0, 1fr);

工作示例:

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 1fr 1fr;
}

.item {
  padding: 3rem;
  border: 1px solid #ccc;
  background: #f4f4f4;
  font-size: 1.3rem;
  font-weight: bold;
  text-align: center;
}

.item:first-child {
  grid-column: 1 / span 3;
  grid-row: 1 / span 2;
  background: blueviolet;
}

.item:nth-child(9) {
  grid-column: 2 / span 3;
  grid-row: 2 / span 2;
  background: red;
}
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
  <div class="item">Item 4</div>
  <div class="item">Item 5</div>
  <div class="item">Item 6</div>
  <div class="item">Item 7</div>
  <div class="item">Item 8</div>
  <div class="item">Item 9</div>
  <div class="item">Item 10</div>
  <div class="item">Item 11</div>
  <div class="item">Item 12</div>
  <div class="item">Item 13</div>
  <div class="item">Item 14</div>
  <div class="item">Item 15</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.