How to align left last row/line in multiple line flexbox

PuZ picture PuZ · May 4, 2013 · Viewed 81.5k times · Source

I have a major issue with flexbox layout. I build a container with a boxes filled with images, and i decided to use flexbox layout to justify the content to make it looks like a grid

Her's the code:

<div class="container">

    <div class="item"></div>
    <div class="item"></div>
    ...
    <div class="item"></div>

</div>

and the CSS:

.container {
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    justify-content: space-around;
    -webkit-justify-content: space-around;
    -moz-justify-content: space-around;
    flex-flow: row wrap;
    -webkit-flex-flow: row wrap;
    -moz-flex-flow: row wrap;
}

.container .item { width: 130px; height: 180px; background: red; margin: 0 1% 24px; }

And everything looks good except the last line/row - when it not contain the same number of element that other lines, centering elements and it broke my grid effect.

http://jsfiddle.net/puz219/7Hq2E/

How to align last line/row to left side?

Answer

Got it. (I think)(this is my first contribution here!)

Imagine a layout which needs to have 4 images per row. w:205 h:174 Problem: Using justify-content:space-around, if the last row doesn´t have 4 images (has 3, 2 or 1), they would not respect the grid, they would spread. So.

Create in the html 3 divs with the class "filling-empty-space-childs" like this.

.filling-empty-space-childs {
    width:205px; /*the width of the images in this example*/
    height:0; /*Important! for the divs to collapse should they fall in a new row*/
}

The flexbox container has display:flex / flex-wrap:wrap; / justify-content:space-around

The last row can have 4, 3, 2, 1 images. 4 images: no problem, this three divs would collapse in a new row since they have no height. 3 images: no problem, one div is going to be in the same row, invisible, and the other two would wrap to a new row, but will collapse since they have no height. 2 images: no problem, two divs are going to be in the same row, invisibles, the rest... collapsed 1 image: no problem, the three divs are going to fill in the space.