Just vertically center one specific flex item

The CSS align-items: center lets you center flex items which are next to each other, so that their horizontal midpoint is on one horizontal line. But recently I had two flex items and only wanted to center the right one, if the left is higher, but not the left one if the right is higher. For that, I cannot use align-items: center, but the solution is not much more complex:

.center-flex-item {
	margin-bottom: auto;
	margin-top: auto;
}

With that, the flex item .center-flex-item will be centered if a higher item sits beneath it, but the other item will not be centered if .center-flex-item is greater.

Update from June 9, 2017: Easier and with the probably more correct CSS rule for the scenario, it looks like that:

.center-flex-item {
	align-self: center;
}

Thanks to Matthias for the hint!

Related posts

Leave a Comment

Your email address will not be published. Required fields are marked *