我尝试构建一个CSS Grid,其中一些条目嵌套在div结构中:
就像这样:
.wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
grid-template-rows: 1;
}
.cent {
grid-column: 2;
grid-row: 1;
}
.left {
grid-column: 1;
grid-row: 1;
}
.right {
grid-column: 3;
grid-row: 1;
}

<div class="wrapper">
<div class="cent">center</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
&#13;
但如果我开始嵌套我的结构,我就无法访问我想要的列:
.wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
grid-template-rows: 1;
}
.cent {
grid-column: 2;
grid-row: 1;
}
.left {
grid-column: 1;
grid-row: 1;
}
.right {
grid-column: 3;
grid-row: 1;
}
&#13;
<div class="wrapper">
<div class="cent">center</div>
<div>
<!-- in reality there would be more divs and rows, I already have problems with one -->
<div class="left">left</div>
<div class="right">right</div>
</div>
</div>
&#13;
有人可以告诉我如何使用嵌套结构实现网格吗?或者我有一个完全错误的方法? (遗憾的是,在代码中更改元素的顺序和结构非常耗时)
答案 0 :(得分:4)
嵌套网格是可能的,但要确保最里面的div的父级本身具有display:grid
。如果你没有,
由于这些项目不是网格的直接子项,因此它们不参与网格布局,因此显示在正常的文档流程中。
(来自MDN: Basic concepts of grid layout。)
所以您需要做的就是将这些样式分配给left
和right
div的父级。
.wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
grid-template-rows: 1;
}
.cent {
grid-column: 2;
grid-row: 1;
}
.cent + div { /* this works for now, but you should choose a better selector for this one */
display: grid;
grid-column: 1 / 4;
grid-row: 1;
}
.left {
grid-column: 1;
grid-row: 1;
}
.right {
grid-column: 3;
grid-row: 1;
}
&#13;
<div class="wrapper">
<div class="cent">center</div>
<div>
<!-- in reality there would be more divs and rows, I already have problems with one -->
<div class="left">left</div>
<div class="right">right</div>
</div>
</div>
&#13;