<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">

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

Guruling Kumbhar Apr 09, 2015

Technology

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:

a responsive or fluid HTML development environment.

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>

HTML structure

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.

Login Form

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

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

Similar Blog

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.