如何在CSS网格布局中指定行高?

时间:2021-12-17 12:03:31

I have a CSS Grid Layout in which I want to make some (middle 3) rows stretch to their maximum size. I'm probably looking for a property similar to what flex-grow: 1 does with Flexbox but I can't seem to find a solution.

我有一个CSS网格布局,我想让一些(中间3)行拉伸到它们的最大尺寸。我可能正在寻找类似于flex-grow的属性:1与Flexbox有关,但我似乎无法找到解决方案。

Note: This is intended for an Electron app only, so browser compatibility is not really a concern.

注意:这仅适用于Electron应用程序,因此浏览器兼容性并不是真正的问题。

I have the following CSS Grid Layout:

我有以下CSS网格布局:

.grid {
  display: grid;
  grid-template-columns: 1fr 1.5fr 1fr;
  grid-gap: 10px;
  height: calc(100vh - 10px);
}

.grid .box {
  background-color: grey;
}

.grid .box:first-child,
.grid .box:last-child {
  grid-column-start: 1;
  grid-column-end: -1;
}

/* These rows should 'grow' to the max height available. */
.grid .box:nth-child(n+5):nth-child(-n+7) {
  grid-column-start: 1;
  grid-column-end: -1;
}
<div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Which creates the following grid:

这会创建以下网格:

如何在CSS网格布局中指定行高?




When none of the boxes contain any content I would like the grid to look something like this:

如果没有任何框包含任何内容,我希望网格看起来像这样:

如何在CSS网格布局中指定行高?

1 个解决方案

#1


24  

One of the Related posts gave me the (simple) answer.

其中一篇相关帖子给了我(简单)答案。

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

显然,grid-template-rows属性上的auto值正好符合我的要求。

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

#1


24  

One of the Related posts gave me the (simple) answer.

其中一篇相关帖子给了我(简单)答案。

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

显然,grid-template-rows属性上的auto值正好符合我的要求。

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}