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

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

注意: 这只适用于 电子应用程序,所以浏览器兼容性并不是一个真正的问题。

我有以下 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>

它创建了以下网格:

Current Grid




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

Preferred Grid

216380 次浏览

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

Use of repeat with grid

When boxes doesn't contain any content and If you want to get rid of the empty box spaces as well than you can use following.

grid-template-rows: repeat(2, auto) repeat(3, 1fr) repeat(2, auto);

Or more compact syntax as last two cell size will be by default auto if not defined:

grid-template-rows: repeat(2, auto) repeat(3, 1fr);

If you want some space in any case than you can use:

grid-template-rows: repeat(2, 10px) repeat(3, 1fr) repeat(2, 10px);

Finally CSS would be

.grid {
display: grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: repeat(2, auto) repeat(3, 1fr);
grid-gap: 10px;
height: calc(100vh - 10px);
}
.periodic-table {
display: grid;
grid-template-columns: repeat(18, 60px);
grid-template-rows: repeat(7, 70px) 40px repeat(2, 70px);
grid-gap: 2px;
}

This code will create 18 columns each of them are 60px, and 7 rows of 70px 8th row will be 40px then again 9th and 10th row will be 70px.

There is also the need to specify the minimum height for the elements, otherwise if they have no content they will disappear.

enter image description here

:root{
--body-margin:10px;
}
body{
margin:var(--body-margin);
}
.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 - calc(2 * var(--body-margin)));
}
.grid div{
min-height:20px;
background-color: grey;
}
.grid
div:nth-child(n+5):nth-child(-n+7),
div:first-child,
div:last-child{
grid-column-start: 1;
grid-column-end: -1;
}
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>