首页 > 解决方案 > CSS:如何设置动态项目数的最后一个网格行?

问题描述

我有我的第一行作为22px并使用grid-auto-rows来制作后续行70px。有没有办法在22px不使用模板的情况下制作最后一行,因为当时我不知道div里面有多少?

.cont {
  background: grey;
  height: 600px;
  display: grid;
  grid-template-rows: 22px;
  grid-auto-rows: 70px;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 3px;
}
.cont div {
  background: red;
}
<div class="cont">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

标签: csscss-grid

解决方案


如果您总是有 3 列,请保持模板行自动并定义元素的高度。70px在某些条件下,除了前 3 个和后 3 个之外,所有的都应该有。

.cont {
  background: grey;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 3px;
  margin:10px;
}
.cont div {
  background: red;
  height:70px;
}

.cont div:nth-child(1), /* 1st */
.cont div:nth-child(2), /* 2nd */
.cont div:nth-child(3), /* 3rd */
.cont div:nth-last-child(1), /* last one */
.cont div:nth-last-child(2):not(:nth-child(3n + 3)), /* before the last if not the last one of a row*/
.cont div:nth-last-child(3):nth-child(3n + 1){ /* before the two last only if the fisrt one of a row*/
  height:22px;
}
<div class="cont">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="cont">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="cont">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>


推荐阅读