CSS: How to Horizontally and Vertically Center Align a DIV Box Programming 15 AUG 2013

css ninja t-shirtAs a rule (well to me anyway), login boxes look their absolute best when centering slap bang in the middle of the page, in other words centered both horizontally as well as vertically!

To achieve this middle of everything trick using plain old CSS is pretty simple, and in this quickfire tutorial example, I’ll show you just how easy it is to end up with a nicely placed DIV block, listing both the required CSS as well as a handy selection of demo HTML.

Let’s begin with the CSS:

html, body {
  height: 100%; //pretty important!
body {
  margin: 0; //doesn't strictly have to be zero, CSS would probably readjust
.loginformbox {
  width: 100%;
  min-height: 120px;
  font-size: 1.5em;
  text-align: center;
.loginformboxcentered {
  display: inline-block;
  vertical-align: middle;
  padding: 20px 50px; //whatever look spretty to you
  font-size: 1em; //note you have to set size, thanks to our zeroing of the parent container's value
  letter-spacing: normal;
.loginformbox .loginformboxcentered {
  width: 800px; //this defines how wide your block is
  margin: 0 auto;
  text-align: left;
 .loginformbox:before {
  content: "";
  display: inline-block;
  vertical-align: middle;
  width: 0;
  height: 100%;
  min-height: inherit;
  max-height: inherit;
  padding: 0;

Right, for the most part pretty self explanatory (actually that’s not completely true. But seeing as this post is kind of for my reference and I don’t really want to comment up all the CSS, I’m going to leave it at that).

Right, now for the HTML:

<div class="loginformbox ">
    	<div class="loginformboxcentered">
    		<h1>My Login Box</h1>
    		<p>A nice and vertically and horizontally centered login box. Nifty.</p>

And to be honest, that’s pretty much it. Copy, paste and off you go!

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.