'How to make flex box with limit 2 elements per row?

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 :)



Solution 1:[1]

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/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zbyso