Home > Back-end >  Does anyone know how I can set a limit to the rows that flexbox can wrap?
Does anyone know how I can set a limit to the rows that flexbox can wrap?

Time:06-01

This is my code:

.wrap-here {
 display: flex;
 gap: 5px;
 flex-wrap: wrap;
 width: 250px;
 overflow: auto;
}

.item {
flex: 0 0 20%;
border: 1px solid black;
padding: 10px;
margin-bottom: 5px;
}
<div >
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
   <div >item</div>
</div>

And instead of what I have, I'd like the flexbox to set a limit to 2 rows of maximum wrap, and it would keep adding items horizontally, like in the following picture: enter image description here

Anyone has any idea how I could do this?

CodePudding user response:

I'm not sure this is achievable with flexbox. I'd highly recommend doing this in grid for much better layout control.

Explanation

flexbox is for one dimensional layouts, while grid is for two dimensional layouts. Yes, flex-wrap will make multiple rows, but you can't control the layout as you want to. The problem with flex-wrap in this scenario is that when applied, it won't cause any overflow, as flex-wrap is used to wrap the items to prevent overflow.

The solution

Since you specified the size with width: 250px I'm going to assume you always want 2 rows. By applying grid-auto-flow: column, the layout will continuously make a new column for each item.

With grid-template-rows: 1fr 1fr, there will always be 2 rows in the layout.

With grid-auto-columns: 20%, each item will be a column taking up 20% of the width of 250px, which is 50px (which is, from what I understand, your preferred size as you specificed a flex-basis: 20%.

By applying overflow-x: auto, there will be a horizontal scrollbar from the content overflowing from the 250px container.

.wrap-here {
  display: grid;
  gap: 5px;
  grid-auto-flow: column;
  grid-template-rows: 1fr 1fr;
  grid-auto-columns: 20%;
  width: 250px;
  overflow-x: auto;
}

.item {
  border: 1px solid black;
  padding: 10px;
  margin-bottom: 5px;
}
<div >
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
</div>

  • Related