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

时间:2018-02-06 08:16:45

标签: html css css3 grid-layout css-grid

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

ONE   TWO
THREE FOUR

如果有5到6个项目,则应覆盖2x3布局,例如:

ONE  TWO  THREE
FOUR FIVE SIX

Codepen Link

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



.grid {
  border: 1px solid gray;
  width: 400px;
  height: 200px;
  grid-gap: 5px;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(2, 50%);
  overflow: hidden;
}

.grid .x22,
.grid .x23 {
  background-color: #1c1c1c;
  color: white;
  font-weight: bold;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.grid .x22 {
  grid-column: span 3;
}

.grid .x23 {
  grid-column: span 2;
}

<h2>2x3</h2>
<div class="grid">
  <div class="x23">first</div>
  <div class="x23">second</div>
  <div class="x23">third</div>
  <div class="x23">fourth</div>
  <div class="x23">fifth</div>
  <div class="x23">sixth</div>
</div>
<h2>2x2</h2>
<div class="grid">
  <div class="x22">first</div>
  <div class="x22">second</div>
  <div class="x22">third</div>
  <div class="x22">fourth</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

如果不使用Javascript,您可以在纯import Component from '@ember/component'; export default Component.extend({ didInsertElement() { this._super(...arguments); this.fetchLikesFromServer().then(like => { this.set('likeable', like.get('length') === 0); }); }, }); CSSquantity queries {{}}}中实现此行为,以了解您有多少孩子。

  

Codepen demo

<强>标记

Flexbox

<强> CSS

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

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


<section>
  <div>1</div>
  ...
  <div>4</div>
</section>

最终结果

enter image description here

答案 1 :(得分:0)

您需要使用querySelectorAll查找网格项的数量,然后您可以运行循环以根据元素数添加所需的类。

<强> Updated Codepen

Stack Snippet

&#13;
&#13;
var div = document.querySelectorAll(".grid div");
for (let i = 0; i < div.length; i++) {
  div.length <= 4 ? div[i].classList.add("x22") : div[i].classList.add("x23")
}
&#13;
.grid {
  border: 1px solid gray;
  width: 400px;
  height: 200px;
  grid-gap: 5px;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(2, 50%);
  overflow: hidden;
}

.grid .x22,
.grid .x23 {
  background-color: #1c1c1c;
  color: white;
  font-weight: bold;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.grid .x22 {
  grid-column: span 3;
}

.grid .x23 {
  grid-column: span 2;
}
&#13;
<div class="grid">
  <div>first</div>
  <div>second</div>
  <div>third</div>
  <div>fourth</div>
</div>
&#13;
&#13;
&#13;

相关问题