Flexbox – Align Last Item in Grid To The Left
Flexbox is great for building 2D grids quickly and easily. It has pretty much replaced the use of the Float property when laying out content. But, one of the issues you might find is how efficiently it spaces your items within the grid…
For example, let’s say we have a grid of profile cards. We set the flexbox property of display: flex;
on their container and use justify-content: space-between;
to spread them evenly on the horizontal axis. This is all good until we have a grid with an odd number of items per row, when the last row displays an even number of items. We get this:
The last two items justify themselves to the edges of our container, leaving a gap in the centre. It doesn’t look good so we want to fix this and align the row to the left, closing the gap.
Fixing this is simple and to do it, we use a pseudo element. Going back to our container, (in this case, my container has a class of .speakers), we use the ::after element to create an empty item. We set the following:
.speakers::after {
content: '';
flex: auto;
}
This empty item has a flex property of auto, making it fill the available space and push the previous element to the left. So we get this:
Much better! If there is an even number, our empty container shifts to the next line, letting our grid do it’s thing properly.
other page
Apparently this does not work in IE ?
What version?
Ik this is old but using ‘::’ in some browsers is still not supported, you need to use ‘:’ to select psuedo elements. Then ofc whatever browsers actually support flexbox.
Thanks! Was able to find exactly what I needed. A very graceful hack!
Very Nice!
How did you manage to keep the padding between your speaker items in the last row?
When I use this elegant hack, it removes all the space between the items in the last row.
So excited when I found this… but my issue is I have two portfolio images on each line using space-between, but I have 7 images. I want the last one to be centered instead of in the first column. Any idea?
Simple and genius! Thanks 🙂