使用 CSS 网格布局跨越所有列/行的项目

新手上路,请多包涵

随着 CSS 网格布局模块即将在 Firefox 和 Chrome 中发布,我想我应该尝试掌握如何使用它。

我试图用一个项目创建一个简单的网格 a 跨越所有行的左侧,与其他项目( bc d , e 等)跨越各个行的右侧。 The amount of items spanning the right side of the rows is variable, so there might be any combination of b , c , d , e 等,所以我使用的是 grid-auto-rows 属性。因此,我无法为 a 定义固定数量的行来跨越,但我希望 a 跨越 所有 可用行。

 #container {
    display: grid;
    grid-auto-flow: column;
    grid-auto-rows: auto;
    grid-template-columns: [left] 4rem [right] 1fr;
    margin: 0rem auto;
    max-width: 32rem;
}
#a {
    background: lightgreen;
    grid-column: left;
    grid-row: 1 / auto;
    justify-self: center;
}
#b {
    grid-area: auto / right;
    background: yellow;
}
#c {
    grid-area: auto / right;
    background: pink;
}
#d {
    grid-area: auto / right;
    background: lightskyblue;
}
#e {
    background: plum;
    grid-area: auto / right;
}
 <div id="container">
    <div id="a">a</div>
    <div id="b">b</div>
    <div id="c">c</div>
    <div id="d">d</div>
    <div id="e">e</div>
</div>

我应该怎么做才能使 a 跨越所有行而不知道最终会有多少行?

原文由 Marlius 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 321
1 个回答

我有同样的情况并找到了一个干净的解决方案。

不要使用巨大的行跨度值,而是尝试:

 grid-column: 1/-1;

由于负数从右开始计数,此代码将 grid-column 指定到最后一列的末尾。

注意:如果这不适用,请在下面的评论中查看 Jonny Green 的解决方案。

原文由 lehoang 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题