The Best Way to Vertically Align in CSS

Phuse
Phuse
Published in
2 min readAug 5, 2013

“The best way to vertically align something in CSS is to close your laptop and head out to the bar.” (Or something to that effect, read in passing on Twitter.) Even in these days of CSS3 where styling has advanced so much, it’s still a pain to vertically center anything.

Until there’s a better way, here’s something that works:

HTML:

<!-- containing element to implement centering trick on -->
<div class="wrapper"><!-- element to center -->
<div class="container">
<h1>Hello World</h1>
Hi, I am page content.
</div>
</div>

CSS:

.wrapper {
/* set the height of the element which contains what you want to center */
height: 100%;
/* these styles are optional, to set width horizontally center the page */
max-width: 500px;
margin: 0 auto;
}
.wrapper:before, .container {
/* these are the important styles for the centered element: */
display: inline-block;
vertical-align: middle;
}
.wrapper:before {
/* this is the important part */
content: '';
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
/* this just takes care of whitespace added by having display:inline-block (there are other methods) */
margin-left: -0.25em;
}

[caption id=”attachment_2199" align=”aligncenter” width=”644"]

valign-screen

View Demo[/caption]

The major benefit of this method over others is that it doesn’t use tables or display:table-cell (which has its own quirks) and the height of the element to be centered doesn’t need to be known. The main drawback is that the containing element needs a set height. You also have to watch for the white-space caused by using display:inline-block and have an extra containing element (as in this example) or text-align properties to horizontally center the box as well. I first came across this idea on a coderwall pro-tip and thought “hey, why didn’t I think of that?” But I don’t like the extra markup, and I see others didn’t either — they’ve since commented with versions using pseudo-elements like this one.

--

--

Phuse
Phuse
Editor for

Phuse is a remote-based design and development agency headquartered in Toronto. We craft websites, interfaces and brands.