Home > Software engineering >  How to make flex box with limit 2 elements per row?
How to make flex box with limit 2 elements per row?

Time:02-10

I need to make a table which will contain up to 4 divs. But the divs in that table always should use maximum of avaliable space. And one one row should contain not more then 2 divs For instance if table contains 2 divs it should look like this enter image description here

If table has 3 divs then like this: enter image description here

And if contains 4 then it should look like that

enter image description here

To achieve it i wrote this code:

<div
  style={{
    height: '58vh', border: '1px solid #d9d9d9',
    borderRadius: '0px 0px 2px 2px',
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
  }}
 >
   <div style={{background:'red', flex: 'auto', margin: '5px'}}
   <div style={{background:'green', flex: 'auto', margin: '5px'}}
   <div style={{background:'blue', flex: 'auto', margin: '5px'}}
   <div style={{background:'pink', flex: 'auto', margin: '5px'}}

 </div> 

But i missing something here. For 1 div and for 2 divs it works as planned. But for more.. This is my result for 3 divs enter image description here And for 4 divs enter image description here Can anyone advice me please what should i change in this code?

PS. Please don't judge my unevenly drawn squeres :)

CodePudding user response:

.container {
  display: flex;
  flex-wrap: wrap;
}

.inner {
  flex-basis: 50%;
  flex-grow: 1;
}

.inner:nth-of-type(1) {
  background: red;
}

.inner:nth-of-type(2) {
  background: gold;
}

.inner:nth-of-type(3) {
  background: green;
}

.inner:nth-of-type(4) {
  background: blue;
}
<div >
  <div >one</div>
  <div >two</div>
  <div >three</div>
  <div >four</div>
</div>

I used the following steps to achieve your result.

  1. Make the container which contains the inner boxes as flex.
  2. Give the container flex-wrap: wrap so that the inner boxes which do not have place on the same line, shift to the next line.
  3. Give flex-basis: 50% to the inner boxes so that they take up 50% of the available space.
  4. Give the inner boxes flex-grow: 1 so that if the last box has any space left, it will take up all of it.

References:

PS: Try commenting the fourth inner box so that the third box will take up the whole horizontal space.

CodePudding user response:

What you mean about use Grid for this?

example:

  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;

here it's guide for Grid: https://css-tricks.com/snippets/css/complete-guide-grid/

  •  Tags:  
  • Related