How to style display: flex elements to show as 3x2x3x2

43 Views Asked by At

This is my code for a website on which I have boxes, which on click lead user to another page for specific article. I use display: flex to show them in a 3x3x3 rows, but I want it to be displayed in a 3x2x3x2 style, so that first row has a width of 33%, but in the second row each box has a width of around 50%. Is it achievable in any way? I can't find any suitable solution on the internet. HTML:

<div class="boxes">

<div class="box">
 <a>
  <div class="photo">...</div>
  <div class="content">...</div>
 </a>
</div>

<div class="box">
 <a>
  <div class="photo">...</div>
  <div class="content">...</div>
 </a>
</div>

<div class="box">
 <a>
  <div class="photo">...</div>
  <div class="content">...</div>
 </a>
</div>

</div>

CSS:

.boxes{
 position: relative;
 width: 100%;
 display: flex;
 flex-wrap: wrap;
 justify-content: center;
 column-gap: 20px;
 rów-gap: 20px;
}

.box{
 display: block;
 position: relative;
 width: calc(33.33%);
}

EDIT: of course I have more of these divs "box" but I just provided less to not make a mess

1

There are 1 best solutions below

6
tacoshy On

You can solve this with a CSS Grid by creating a 6-column grid. Then you let all elements span 2 rows and select every 4th and 5th element of a group of 5 elements to span 3 columns.

section {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
}

section > div {
  grid-column: span 2;
}

section > div:nth-child(5n + 4),
section > div:nth-child(5n + 5) {
  grid-column: span 3;
}

/* for visualisation purpsoe only */
div {
  min-height: 20vh;
  border: 2px dashed red;
  display: flex;
  justify-content: center;
  align-items: center;
}
<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</section>

You also can do this with Flexbox, however which will not allow the usage with gap without complicated calculations. Here you can also sue the nth-child() selector to select the 4th and 5th element of a group of 5 elements:

section {
  display: flex;
  flex-wrap: wrap;
}

section > div {
  width: calc(100% / 3);
  box-sizing: border-box;
}

section > div:nth-child(5n + 4),
section > div:nth-child(5n + 5) {
  width: 50%;
}


/* for visualisation purpsoe only */

div {
  min-height: 20vh;
  border: 2px dashed red;
  display: flex;
  justify-content: center;
  align-items: center;
}
<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</section>