如何将嵌套的 DIV 放置在具有可变行高的 CSS 网格中?

How to place nested DIVs in a CSS grid with variable row heights?

我需要将 4 个 div 容器放在 2 x 2 矩阵中。列的宽度必须相等(因此是固定的),而行的高度必须适应单元格的内容(因此是可变的)。

只要标记结构看起来像这样,这就很容易做到:

<div class="wrapper">
  <div class="cell a1">...</div>
  <div class="cell a2">...</div>
  <div class="cell b1">...</div>
  <div class="cell b2">...</div>
</div>

对应的 CSS 看起来像这样:

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

不幸的是,我的标记(我无法轻易更改)包含嵌套标记结构中的单元格:

<div class="wrapper">
  <div class="container">
    <div class="cell a1">...</div>
    <div class="cell a2">...</div>
  </div>
  <div class="container">
    <div class="cell b1">...</div>
    <div class="cell b2">...</div>
  </div>
</div>

只要两行的高度可以相等,声明.container为二级网格就解决了。但是由于行高必须根据单元格内容进行调整,所以这个不行。

有没有办法将所有四个 div.cell 放在由 div.wrapper 定义的同一个网格中,尽管它们不是直接子元素?

您正在寻找的是Subgrid目前(2021 年 12 月)的功能仅在 Firefox Nightly 上测试过。

关于此 CSS 属性的信息 (from the Mozilla Web Docs page) :

When you add display: grid to a grid container, only the direct children become grid items and can then be placed on the grid that you have created.

You can "nest" grids by making a grid item a grid container. These grids however are independent of the parent grid and of each other, meaning that they do not take their track sizing from the parent grid. This makes it difficult to line nested grid items up with the main grid.

For example, if you use grid-template-columns: subgrid and the nested grid spans three column tracks of the parent, the nested grid will have three column tracks of the same size as the parent grid.

当该功能可用并被多个浏览器支持时,下面的示例将起作用(我猜):

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}
.wrapper {
  display: grid;
  height: 100vh;
  width: 100vw;
  background: grey;
  grid-auto-flow: rows;
  grid-template-columns: auto auto;
  grid-template-rows: auto auto;
}
.container {
  display: grid;
  grid-column: 1 / 3;
  grid-row: 1 / 3;
  grid-template-columns: subgrid;
  grid-template-rows: subgrid;
}
.a1{
  background-color: blue;
  grid-row: 1;
  grid-column: 1;
}
.a2{
  background-color: yellow;
  grid-row: 1;
  grid-column: 2;
}
.b1 {
  background-color: red;
  grid-row: 2;
  grid-column: 1;
}
.b2 {
  background-color: green;
  grid-row: 2;
  grid-column: 2;
}
<div class="wrapper">
  <div class="container a">
    <div class="cell a1">A1</div>
    <div class="cell a2">A2</div>
  </div>
  <div class="container a">
    <div class="cell b1">B1</div>
    <div class="cell b2">B2</div>
  </div>
</div>

并且会呈现如下内容: