在CSS Grid中使列跨越所有行(包括隐式行)

7
我试图使网格列跨越每一行,包括隐含的行。
我遇到了这个问题,问如何跨越所有网格行。第二个答案有一个更好的解决方案。这似乎可以工作,但我的例子和第二个答案的评论表明它不起作用。 W3规范也给出了非常接近的示例。
我的代码有问题吗?还是Firefox、Chrome和Safari可能存在错误? 我在CodePen中也有这个例子

* {
  box-sizing: border-box;
}

.container {
  border: 1px solid #666;
  max-width: 1000px;
  padding: 10px;
  display: grid;
  grid-template-columns: 150px 1fr 300px;
  /* grid-template-rows: repeat(auto) [rows-end]; Doesn't seem to help */
  /* grid-template-rows: [rows-start] repeat(auto) [rows-end]; Doesn't seem to help */
  grid-template-rows: repeat(auto);
  grid-gap: 10px;
  margin: 10px auto;
  grid-auto-flow: row dense;
  /*   justify-items: stretch; */
  /*   align-items: stretch; */
}

.container>* {
  grid-column: 2 / 3;
  padding: 10px;
  outline: 1px solid #666;
}

.pop {
  grid-column: 1 / 2;
  /* grid-column: 1 / -1; If I switch to this, this div will span the full width of the grid, which is exactly what I'm trying to do with rows*/
}

.tertiary {
  grid-column: 1 / 2;
}

.secondary {
  grid-column: 3 / 3;
  grid-row: 1 / -1;
  /* Doesn't work */
  /* grid-row: rows-start / rows-end; Doesn't work */
  /* grid-row: 1 / rows-end; Also doesn't work */
  /* grid-row: 1 / span 7; This works, but I need to span an unknown number of rows*/
  /* grid-row: 1 / span 99; This is gross and creates 99 rows */
}
<div class="container">
  <div class="secondary">Secondary - why doesn't this span all the way to the bottom of the grid?</div>
  <div class="tertiary">Tertiary</div>
  <div class="tertiary">Tertiary</div>
  <div class="tertiary">Tertiary</div>
  <div>Primary</div>
  <div>Primary</div>
  <div>Primary</div>
  <div class="pop">Span tertiary and primary</div>
  <div>Primary</div>
  <div class="tertiary">Tertiary</div>
  <div>Primary</div>
  <div>Primary</div>
</div>

1个回答

5

您面临两个障碍。

首先,您在.container规则中的CSS代码行:

grid-template-rows: repeat(auto);

这段代码无效。在repeat()符号中的参数必须以正整数开头,该数字指定了重复的次数。由于缺少该参数,所以代码无法工作。更多详细信息请参阅规范

其次,即使上面的代码是正确的,比如说:

grid-auto-rows: auto; (which happens to be the default setting anyway)

您的列仍然不能跨越所有行。

这是因为,正如您可能在引用的另一个答案中看到的那样,轨道定义只能在显式网格中覆盖所有垂直轨道。

所以这将起作用:

grid-template-rows: repeat(6, auto);

修订后的演示

问题的其他部分在您引用的另一个答案中有详细介绍。


2
感谢您对无效行代码的澄清。所以我回到了我的实际原始需求——当有未知数量的行时,是否有一种方法使第三列跨越整个底部? - freshyill
1
是的,那个问题在其他帖子中已经探讨过了。这是社区迄今为止使用纯CSS想出的最佳方法。在网格布局中似乎没有清晰的解决方案。 - Michael Benjamin
或者,您可以直接定位网格项:https://dev59.com/8FYO5IYBdhLWcg3wIuLp - Michael Benjamin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接