Vertical Centering HTML Elements

Posted on May 01, 2017

css flexbox

I dont' know how many of you have tried to vertically center HTML elements before, but it can be a big pain in the butt. A coworker had once given me some hints and a couple of CSS classes that I could use to achieve it. It really wasn't easy though, and hard to have other people come behind and know what's going on.

This is what my coworker suggested:

		.vertical-container:before {
			content: '';
			display: inline-block;
			vertical-align: middle;
			height: 100%;
		}
		.vertical-center {
			display: inline-block;
			vertical-align: middle;
		}
		

This doesn't look wildly complicated, but you have to put the .vertical-container class on a parent element, but not the .container element. So essentially it looked like this:

<div class="container">
	<div class="vertical-container">
		<div class="vertical-center">
			...
		</div>
	</div>
</div>
		

There are also some unintended side effects that can pop up, but don't always. Sometimes the element that you want to vertically center ends up showing after the .container element, and the way to get around it is to set the .vertical-container element's font-size to 0. Then you have to reset the font size on individual elements inside the .vertical-center element. This is obviously not ideal.

Flexbox

Today I started doing @geddski's Flexbox Zombies course. It's great. I've only done about 10 minutes of the course, and learned that I could vertically center elements (without side effects) with three style attributes:

		.vertical-center {
			display: flex;
			flex-direction: column;
			justify-content: center;
		}
		

That's it. No nesting elements, no font-size hacks, nothing. Just a simple class with some simple flexbox properties, and that's that. You can also center align a div, or put it at the beginning or end of the row, as well as top or bottom of the column. I know there is a lot more to learn, and I'm excited to understand and implement it. I can already see how making a responsive column layout will be much more simple with flexbox than it was before!

Anyways, flexbox seems to be legit, and will make awesome layouts much more achievable. Go check out Flexbox Zombies so you can learn how to use flexbox as well!