Vertical alignment is one of the most common tasks for anyone converting a design into an HTML page. Back in the days, it used to be tables! Tables used to be the solution to any problem regarding layouts. Although it is not yet widely supported, CSS3 brought us new solutions to our problems, one of them is: Vertical alignment and positioning in CSS.

Browser Support

Since it is a relatively new property, it is not yet fully supported by the browsers in use. Yes you guessed it! Microsoft browsers (Internet Explorer and Edge) are the ones in question!

Browser Support - Credits: Caniuse.com

Browser Support - Credits: Caniuse.com

As you might have noticed, CSS Flexbox is supported by most of the major browsers (web and mobile) with their latest versions, with the exceptions of IE 11 (partial support due to many bugs in rendering) and Microsoft Edge ( the "new" browser that comes with Windows 10).

Well, if you don't care about Microsoft browsers (or the headache of hacking the bugs), feel free to use CSS flexbox :D.

Now let's get to business!

The HTML

Vertical alignment requires a parent, and children. Alignment CSS will be applied to the parent, and styling CSS to the children.

[codesyntax lang="html4strict"]

<div class="flexbox-container">
	<div>Lorem ipsum dolor sit amet</div>
	<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
</div>

[/codesyntax]

 

The CSS

CSS flexbox only needs to be applied to the parent in order to align the children vertically.

[codesyntax lang="css"]

.flexbox-container {
	display: -ms-flexbox;
	display: -webkit-flex;
	display: flex;

	-ms-flex-align: center;
	-webkit-align-items: center;
	-webkit-box-align: center;

	align-items: center;
}

[/codesyntax]

Aside from browser specific CSS (vendor prefix: -webkit, -ms, -moz), it's a very straightforward approach as long as you don't have to support old browsers.

 

Check my blog regularly for new tips in CSS, HTML, and maybe Angular JS. No one knows.