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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41916722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:19:21  来源:igfitidea点击:

How do I specify row heights in CSS Grid layout?

htmlcssgrid-layoutcss-grid

提问by Chris

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: 1does with Flexbox but I can't seem to find a solution.

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

Note: This is intended for an Electronapp 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:

这将创建以下网格:

Current Grid

当前网格




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




当没有一个框包含任何内容时,我希望网格看起来像这样:

Preferred Grid

首选网格

回答by Chris

One of the Related postsgave me the (simple) answer.

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

Apparently the autovalue on the grid-template-rowsproperty does exactly what I was looking for.

显然auto,该grid-template-rows物业的价值正是我所寻找的。

.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);
}