Flexbox – Repeat layout depending on items shown

0

Issue

I am trying to create a masonry style layout using flexbox, I am aiming for something that looks like this..

enter image description here

I can create the layout simply enough, but I would like the layout to repeat depending on the number of items shown.

Anyone have an example of something similar or any guidance on how to tackle it?

I was thinking of doing some PHP handling first to work out how many items there are and then generating the layout, not sure if this is the best way to achieve it though.

Solution

You can do this with Flexbox you just need to use flex-wrap: wrap and set width of first two items of 5 to 50% and other 3 to 33.33%. Also you need to include margin in items width.

* {
  box-sizing: border-box;
}
.layout {
  display: flex;
  flex-wrap: wrap;
}
.item {
  height: 100px;
  margin: 5px;
  border: 1px solid black;
}
.item:nth-child(5n + 1),
.item:nth-child(5n + 2) {
  height: 150px;
  background: blue;
  flex: 0 0 calc(50% - 10px);
}
.item:nth-child(5n + 3),
.item:nth-child(5n + 4),
.item:nth-child(5n + 5) {
  background: blue;
  flex: 0 0 calc(33.33% - 10px);
}
<div class="layout">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

You can also do this with Grid-Layout by using grid-template-columns: repeat(6, 1fr) and then making first two items span 3 and other 3 span 2. This means that the first 2 items will each take 3fr units of 6 and other 3 will take 2fr units of 6.

* {
  box-sizing: border-box;
}
.layout {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(6, 1fr);
  grid-auto-rows: 150px 100px;
}
.item {
  border: 1px solid black;
}
.item:nth-child(5n + 1),
.item:nth-child(5n + 2) {
  grid-column: span 3;
}
.item:nth-child(5n + 3),
.item:nth-child(5n + 4),
.item:nth-child(5n + 5) {
  grid-column: span 2;
}
<div class="layout">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Answered By – Nenad Vracar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More