Home > Software engineering >  How to get items break to next row if they exceeds to 3 columns with flexbox css
How to get items break to next row if they exceeds to 3 columns with flexbox css

Time:10-02

I'm trying to loop an array of objects and display them in grid view but with the flexbox concept in CSS.

<div >
  <div >
    <div >1</div>
    <div >2</div>
    <div >3</div>
    <div >4 (to go to row 2 if there is 4)</div>
  </div> 
</div>
.container { 
  width: 100%; 
  background-color: red; 
}

.innercontainer {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.item {
  flex: 1;
  background-color: yellow;
  padding: 30px;
}

The above code works perfectly fine until 3 items. When 4th item comes, I want it to go to the next row.

I tried some research and did this but not working.

<div >
  <div >
    <div >1</div>
    <div ></div>
    <div >2</div>
    <div ></div>
    <div >3</div>
    <div ></div>
    <div >4 (to go to row 2 if there is 4)</div>
    <div ></div>
  </div> 
</div>

I appended this css code to above css, but not working.

.breaker {
  display: none;
}
.breaker:nth-child(3n) {
  display: block;
  width: 100%;
  height: 0;
}

You can see them in codepen. (enter image description here

With my first implementation, I have achieved the first 2 scenarios from the picture.

CodePudding user response:

Try adding flex-basis: 25%; to your .item class. Usually, 33% would work but since you have padding in the item class, you might have to play around with it a bit.

flex-basis: https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis

In my experience using grid instead of flex is better here.

CodePudding user response:

.item{ background-color: yellow;

width: 33%;

flex-grow: 1; }

CodePudding user response:

Use CSS grid for this:

.container {
  display: grid;
  grid-auto-flow: column;
  gap: 5px;
  border: 1px solid;
  margin: 20px 0;
}

.container > div:nth-child(3n   1) {grid-column: 1}
.container > div:nth-child(3n   2) {grid-column: 2}
.container > div:nth-child(3n   3) {grid-column: 3}


.container > div {
  height: 50px;
  background: red;
}
<div >
  <div></div>
</div>

<div >
  <div></div>
  <div></div>
</div>

<div >
  <div></div>
  <div></div>
  <div></div>
</div>

<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

  • Related