【问题标题】:How to fit CSS grid layout items when there is not enough item [duplicate]当没有足够的项目时如何适应CSS网格布局项目[重复]
【发布时间】:2020-11-13 21:00:30
【问题描述】:

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

看下图就是我想做的,也做到了:

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

所以这是我的问题:我如何才能制作出动态的东西? 我的意思是当我没有足够的物品时,可以在包装中安装其他物品,如下所示:

【问题讨论】:

  • CSS-Grid 无法自动执行此操作。这就是 flexbox 的设计目的。
  • @Paulie_D 你是对的,但是对于 flex 布局,我必须将左右两侧放在一个 wapper 中,我需要设计的布局项目不应该在 wrapper 中。

标签: css layout css-grid


【解决方案1】:

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

您可以做的是设置 CSS 以匹配不同的情况:

从 5 到 1 个孩子的演示

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>

【讨论】:

  • 完美!谢谢。
猜你喜欢
  • 2021-05-11
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
相关资源
最近更新 更多