e-Zest members share technology ideas to foster digital transformation.

Tutorial: How to vertical center align a login form or container DIV?

Written by Guruling Kumbhar | Apr 9, 2015 5:32:05 PM

Often times, HTML developers are faced with a task of developing a login page where the form has to be horizontally and vertically aligned. To tackle this, some developers use margin from top and left to align the form centered to the parent container element.

While it may work for the fixed page size layout, it may not work in a responsive or fluid HTML development environment.

Refer to the image below:

You can vertically align <form> or any container element through the following ways:

  • Using media query for every screen size and device and specifying top margin for each one.
  • By using JavaScript to calculate and assign the top margin to the form container each time a page loads.
  • By using css3 calc() method

For cross-browser and pixel-perfect solution, you can follow the method described below:

Step 1 –

  • Create the following HTML structure:
<div class="grandParentContaniner">
<div class="parentContainer">
<form>
             		Your Form Code will be here...
		</form>
</div>
</div>

Step 2 –

Add css in your css file of inside <style> like below:

Html, body{
		height:100%;
	}

	.grandParentContaniner{
		display:table; height:100%; margin: 0 auto;
	}

	.parentContainer{
		display:table-cell; vertical-align:middle;
	}	

By following the steps outlined above, the ‘Login Form ’ can be aligned vertically and centered horizontally.

The great part is that it can work on older browsers such as IE8 and below as well.

I have also created a demo on the Plunker and jsfiddle.

Kindly note that Plunker and jsfiddle will not work below IE9.