当没有足够的项目时如何适应 CSS 网格布局项目

How to fit CSS grid layout items when there is not enough item

我正在尝试使用 CSS 网格制作布局。 起初,我用网格制作网站来处理它,一切都很可靠,然后我才意识到问题是:我的布局不是动态的

看下图是我想做的并且做到了:

现在,当我删除其中一个网格子项时,会发生这种情况:

所以这是我的问题:我怎样才能制作出动态的东西? 我的意思是,当我没有足够的物品时,可以在包装纸中放入另一件物品,如下所示:

grid允许合并行和列,flex,是其中之一。

您可以做的是设置 CSS 以匹配不同的大小写:

演示从 5 到 1 child

html {
  display: grid;
  min-height: 100vh;
}
body {
  margin: auto;
  display: flex;
  flex-wrap:wrap;
}
.grid {
  width: 40vh;
  height: 20vh;
  margin: auto;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 5px;
  margin: 5px;
  padding: 5px;
  background: tomato;
  counter-reset:divs
}
.grid:nth-child(even) {
  background: crimson;
}
.grid div:before {counter-increment:divs;content:counter(divs)}
.grid div {
  background: gray;
}
.grid div:nth-child(1),
.grid div:nth-last-child(1):nth-child(2) {
  grid-row: span 2;
  grid-column: span 2;
}
.grid div:nth-last-child(1):nth-child(even) {
  grid-column: span 2;
}
.grid div:nth-last-child(2):nth-child(2),
.grid div:nth-last-child(2):nth-child(2) + div {
  grid-column: span 2;
}

.grid div:last-child:first-child {
  grid-column: span 4;
}
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div> 
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div> 
</div>
<div class="grid">
  <div></div>
  <div></div> 
</div>
<div class="grid">
  <div></div> 
</div>