The key is to make your five sub-divs (inside #mainContainer
) to be 25% width, not 250px.
Consider: inside the mainContainer, you have the five sub-divs (let's call them the outer divs), which are four-to-a-line (or 25% width) and inside each outer div you have an inner div. (The purpose of the inner div is only to align the contents inside each of the five sub-divs)
You need flex on the mainContainer in order to (a) align the five sub-divs in a line, and (b) to wrap onto the next line (flex-wrap
).
Each of those five sub-divs should be 25%, not ___px. That way, the fifth (and 9th, and 13th, etc) will wrap to the next line. Also, your solution will be responsive - which means that as the screen size changes, you'll still get 4-to-a-line. And also, because you are using the .inner
div to align the content, the spill-over divs (5th, 9th, 13th, etc) can be left-aligned.
To be clear: you do not need the "inner" div structure that I added to your example. But if you want the contents of the five (or more?) sub-divs to be centered, then create divs inside each sub-div - and make each of those (".inner") divs also flex, and align the contents using justify-content
(horizontal) and align-items
(vertical).
body{
width:100%;
}
.mainContainer{
width:90%;
background-color : brown ;
display:flex;
flex-basis:25%;
flex-wrap:wrap;
}
.outer{
width:25%;
height:100px;
}
.inner{
width:100%;
height:100%;
display:flex;
justify-content:center;
align-items:center;
}
.div1{
background-color:blue;
}
.div2{
background-color:red;
}
.div3{
background-color:green;
}
.div4{
background-color:purple;
}
<div class="mainContainer">
<div class="outer div1"><div class="inner">div1</div></div>
<div class="outer div2"><div class="inner">div2</div></div>
<div class="outer div3"><div class="inner">div3</div></div>
<div class="outer div4"><div class="inner">div4</div></div>
<div class="outer div2"><div class="inner">div5</div></div>
</div>
Update:
I just re-read your question. If you want the 4th div to start on a new line, and at the beginning of the line, the only way I can think to do that is to add yet another wrapping div structure, so that there is a "row" div that contains your ".outer" divs. Your ".outer" divs are width: 25%, so they will not expand to fill the full row. Also, if you have just one inside a .row div, it will begin at the left.