thairish thairish - 4 months ago 20
HTML Question

Why are flex items not wrapping?

I am attempting to make multiple rows of squares (3 per line) which have the same height.

I have written some HTML and CSS for this but the boxes all go on the same line.

Here's what I have so far:



#list-wrapper {
display: flex;
width: 100%;
}
#list-wrapper div {
width: 33.33%;
}
#list-wrapper div img {
flex: 1;
}

<div id="list-wrapper">
<div>
<img src="images/1.png" alt="image one" />
</div>
<div>
<img src="images/2.png" alt="image two" />
</div>
<div>
<img src="images/1.png" alt="image one" />
</div>
<div>
<img src="images/2.png" alt="image two" />
</div>
<div>
<img src="images/1.png" alt="image one" />
</div>
<div>
<img src="images/2.png" alt="image two" />
</div>
</div>





When I load the page with this all boxes appear but they are all on one line going over the parent div's 100% width.

Any help is much appreciated.

Answer

If you are using flexbox and want the content to wrap, you must specify flex-wrap: wrap. By default flex items don't wrap.

Your code here is doing nothing because the parent of #list-wrapper div img is not display: flex. You need to move this to #list-wrapper div:

#list-wrapper div img {
    -webkit-flex: 1;
    -ms-flex: 1;
    flex: 1;
}

To have the images be three-across, you should specify flex-basis: 33.33333%.

Change your CSS to this and it will work:

#list-wrapper {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    width: 100%;
    flex-wrap: wrap;
}

#list-wrapper div {
    flex: 0 0 33.333%;
}

JS Fiddle: https://jsfiddle.net/f47prnnt/1/