Search code examples
csspositionflexbox

display divs always in 3 columns regardless of their heights in flex parent


I need divs always to display in 3 columns regardless of their heights in flex parent and number of the divs (it can be 10 or more - but always in 3 columns - underneath each other) How do I make it? Code Pan example appreciated.

EDIT:

<div class='main'>
<div class='div'>1</div>
<div class='div'>2</div>
<div class='div'>3</div>
<div class='div'>4</div>
</div>

.main {display:flex;flex-direction:row;background:silver;}
.div {width:33%; height:10px;background:gold;margin:10px;}

Here is my EXAMPLEhttp://codepen.io/broudi/pen/MyVNyz - there are 4 equal divs in parent flex div. I need no matter how much divs there are in parent div always to situate them in 3 columns(so one underneath another if first 3 places are taken).

NEW EDIT: ANOTHER PROBLEM: HERE IS MY CODE:http://codepen.io/broudi/pen/MyVNyz

The problem is that if one or more of thechild dovs have height different then others then the div below doesnt go as it supposed to. it takes some space. Please, check out my CODEPAN example. How can I makkw inner divs no matter what go one after another with equal 5px margin regardless of their heights?


Solution

  • you have to give the parent flex-wrap:wrap; andto the div 30% not 33% because of the margin:10px; and now you will always have a row of 3 div's

    even put in justify-content:space-around; or between for that it looks better

    .main {display:flex;flex-direction:row;background:silver; flex-wrap:wrap; justify-content:space-around;}
    .div {width:30%; height:10px;background:gold;margin:10px;}
    <div class='main'>
       <div class='div'>1</div>
       <div class='div'>2</div>
       <div class='div'>3</div>
       <div class='div'>4</div>
       <div class='div'>5</div>
       <div class='div'>6</div>
       <div class='div'>7</div>
       <div class='div'>8</div>
       <div class='div'>9</div>
       <div class='div'>10</div>
       <div class='div'>11</div>
       <div class='div'>12</div>
    </div>