Centering The Last Item In A Flexbox Container

I’m using flexbox more and really liking it, I’ve hit an issue a few times with center aligning the last item in an uneven row of elements inside a flexbox row container when using the justify-content: space-between; flexbox property, you could use  justify-content: flex-start; – but when that won’t do, here is a solution  below.

So in  the example image below there is a number of testimonials as list items in an unordered list but they are uneven…

flexbox-center-last-item

The CSS to get to it…

ul {
 display: flex;
 flex-flow: row wrap;
 justify-content: space-between;
 }

The list items are set to a defined width…

li{
width:30%;
}

But we have the last item following the space-between property and positoning itself to the edge of the container, you most probably want that last item aligned in the center, what we can do is use the after pseudo selector and add in some blank content after the <ul> container set the same size as the list item.

ul:after {
 content: "";
 flex: 0 1 30%;
 }

So here we are using the flex property with the after psuedo on the container.

The flex property is shorthand for 3 properties, flex-grow, flex-shrink, flex-basis – you could instead set the flex-grow property to 1 so it grows in the space, but I find setting the flex-basis has better results.

flex-basis is the third value given and can also be given other increment values such as px

flexbox-center-last-item-flex-width

Similarly for a 4-column layout where your items are set t0 25% and you have 4 in the first row and only 2 in the second, you would adjust your flex-basis value on the container to double the item, so 50%  – then the items would shift left aligning them nicely.

 

Ref

Leave a Comment





%d bloggers like this: