CSS Flex grid - Same width for last item
Set the flex grow to 0.
fiddle: http://jsfiddle.net/RichAyotte/Ev5V7/
<div class='flex-container seven'>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
.flex-container {
display: flex;
flex-flow: row wrap;
justify-content: flex-start;
}
.flex-container div {
font-size: 200%;
padding: 2mm;
margin: 10px 10px;
flex: 0 1 20%;
box-shadow: 3px 3px 2px 0px rgba(50, 50, 50, 0.5);
}
It's a common misconception, but Flexbox is not a grid system. Once the flex items are set to be flexible, they can only be sized relative to the other flex items on the same line, not with the flex items on any other line. There is no way to force them to line up without using a specific width (though this width can be a percentage).
Your min-width serves no purpose here since your flex items are flexible. Your flex-shrink value serves no purpose because your flex items are allowed to wrap. The max-width is the only thing preventing the items on the last line from filling the entire row. You would have to know the exact width of the items in the preceding row in order to set the correct max-width value.
Related:
- Flex-box: Align last row to grid
- Left aligned last row in centered grid of elements
CSS
.box {
display: grid;
grid-template-columns: repeat(auto-fill,minmax(160px, 1fr));
}
HTML
<div class="box">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
<div>Eight</div>
<div>Nine</div>
<div>Ten</div>
</div>
Using a flex box you have to be careful about your max-
and min-
widths. Quoting from w3schools:
Tip: Elements that are flexible can shrink or grow as the box shrinks and grows. Whenever there is extra space in a box, flexible elements are expanded to fill that space.
To counteract this, initiate a width of X number pixels for your container but use percentages instead of your pixel amounts for the interior boxes. The percentage of the container will be the same for all your columns.
Doing this also removes the need for a flex box because those are only if you want expansion of the boxes in the horizontal direction (making them wider based on content of each one) rather than vertical direction.
PS - if you want this responsive and to keep the widths proportional to the space in between as well, use percentages for your margins as well (but keep in mind border and padding sizes). This isn't necessary but is a useful feature for keeping a consistent look and feel on different devices.