css-grid 2x2 或 2x3 布局,取决于项目的数量

Tim*_*imm 4 html css grid-layout css-grid

考虑一个项目数量可变的计划,在 1 到 6 之间。如果有 1 - 4 个项目,它们应该覆盖 2x2 布局,例如:

ONE   TWO
THREE FOUR
Run Code Online (Sandbox Code Playgroud)

如果有 5 - 6 个项目,它们应该覆盖 2x3 布局,例如:

ONE  TWO  THREE
FOUR FIVE SIX
Run Code Online (Sandbox Code Playgroud)

代码笔链接

但是,我需要以编程方式将x22x23类应用于项目,具体取决于项目的数量。我更喜欢在我的模板中不需要额外逻辑的解决方案。

fca*_*ran 7

如果不使用Javascript,你可以实现纯这种行为CSSFlexbox和几个数量查询知道你有几个孩子。

代码笔演示


标记

<section>
  <div>1</div>
  ...
  <div>6</div>
</section>

<section>
  <div>1</div>
  ...
  <div>5</div>
</section>


<section>
  <div>1</div>
  ...
  <div>4</div>
</section>
Run Code Online (Sandbox Code Playgroud)

CSS

section {
  margin-bottom: 4rem;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; }


/* by default assign flex-basis to 49.75% (2 boxes per row) 
 * the gap between box is .5%
 */

div { 
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 49.75%;
  margin-bottom: .5%;  }

/* if parent element contains at maximum 5 or 6 children we set their
 * flex-basis to 33% (3 boxes per row, gap is still .5%)
 */

div:nth-last-child(n+5):first-child,
div:nth-last-child(n+5):first-child ~ *,
div:nth-last-child(n+6):first-child,
div:nth-last-child(n+6):first-child ~ * {
  flex-basis: 33%; }


/* since we're setting space-around to `justify-content` we need to
 * remove the extra space on the last row when we have exactly 5 
 * children, by adjusting the margin on the last child  
 */ 
div:nth-child(5):last-child {
  margin-right: auto;
  margin-left: .5%; } 
Run Code Online (Sandbox Code Playgroud)

最后结果

在此处输入图片说明