Flex-box: Align last row to grid
Add a ::after
which autofills the space. No need to pollute your HTML. Here is a codepen showing it: http://codepen.io/DanAndreasson/pen/ZQXLXj
.grid {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
}
.grid::after {
content: "";
flex: auto;
}
As other posters have mentioned - there's no clean way to left-align the last row with flexbox (at least as per the current spec)
However, for what it's worth: With the CSS Grid Layout Module this is surprisingly easy to produce:
Basically the relevant code boils down to this:
ul {
display: grid; /* 1 */
grid-template-columns: repeat(auto-fill, 100px); /* 2 */
grid-gap: 1rem; /* 3 */
justify-content: space-between; /* 4 */
}
1) Make the container element a grid container
2) Set the grid with auto columns of width 100px. (Note the use of auto-fill (as apposed to auto-fit
- which (for a 1-row layout) collapses empty tracks to 0 - causing the items to expand to take up the remaining space. This would result in a justified 'space-between' layout when grid has only one row which in our case is not what we want. (check out this demo to see the difference between them)).
3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.
4) Similar to flexbox.
ul {
display: grid;
grid-template-columns: repeat(auto-fill, 100px);
grid-gap: 1rem;
justify-content: space-between;
/* boring properties */
list-style: none;
background: wheat;
padding: 2rem;
width: 80vw;
margin: 0 auto;
}
li {
height: 50px;
border: 1px solid green;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>