Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does anyone know how I can set a limit to the rows that flexbox can wrap?

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 class="wrap-here">
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">item</div>
   <div class="item">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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you specified the size with width: 250px I’m going to assume you always want 2 rows.

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

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% width in each row. 5 * 20% is 100%, so after 5 items, the items will go into the second row.

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 class="wrap-here">
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
  <div class="item">item</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading