Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make flex items wrap two at a time

Tags:

What I have now is when the window re-sizes, the boxes adjust accordingly to fit the width. However, what I want is to have a minimum of two boxes move to the next line instead of 3 on top and 1.

Is this achievable with flexbox and if not, how would I accomplish this?

fiddle: https://jsfiddle.net/jzhang172/cqdwLyxu/

.line{
  display:flex;
  width:100%;
  margin-bottom:30px;
  flex-wrap:wrap;
  align-items:center;
  justify-content:center;
  
}
body,html{
  margin:0;
  padding:0;
  position:relative;
}
*{
  box-sizing:border-box;
}
.box{
  width:200px;
  min-width:200px;
  background:blue;
  margin:0 10px 0 10px;
  height:200px;
}
<div class="line">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
<div class="line">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
like image 355
Snorlax Avatar asked Mar 15 '16 21:03

Snorlax


People also ask

How do you flex 3 items per row?

For 3 items per row, add on the flex items: flex-basis: 33.333333% You can also use the flex 's shorthand like the following: flex: 0 0 33.333333% => which also means flex-basis: 33.333333% .

How do you align two flex items side by side?

Just use flex-direction: row with flex-wrap: wrap . Then make each element long enough to occupy a full row. Reduce the flex-basis on the elements that are to share a row. With flex-grow: 1 defined in the flex shorthand, there's no need to use calc() .

How do you wrap elements in Flex?

Making things wrap If you want to cause them to wrap once they become too wide you must add the flex-wrap property with a value of wrap , or use the shorthand flex-flow with values of row wrap or column wrap . Items will then wrap in the container.


1 Answers

You can use a media query that changes the flex-basis to 50% on wrap, forcing two items per line.

Add this to your CSS:

@media ( max-width: 800px ) {
    .box {
           flex-basis: calc(50% - 20px);
           margin: 10px; 
         }
}

Revised Demo

like image 116
Michael Benjamin Avatar answered Oct 12 '22 10:10

Michael Benjamin