One of the most common queries all the new front End developers have is ” How do we center align a DIV? “.

Well, let me tell you that it is one of the easiest task. Let’s take a look at how to center align a Div.

Center align a Div horizontally

A Div can be easily center aligned Horizontally using simple CSS properties. All that you need to do is to give the Div a width value less than 100% or less than its parent’s width and set the left and right margin to auto. The following example shows CSS property required.

<style type="text/css">
margin:0 auto;

<div class="myDiv">
Div data goes here

 Center align a Div vertically

Sometimes you would want your Div to be center aligned vertically. Unfortunately there is no easy CSS way to do it like in case of horizontally center aligning the Div. An easy way would be to use javascript to handle the situation. The following function can help you center align a div vertically. Its built around jQuery but if need be you can convert it to plain javascript version too.

//Usage : verticalAlign('classOfDiv');
function verticalAlign(elemClass){
var wndHeight = $(window).height();
	var divHght = $("."+elemClass).height();
	if(wndHeight > divHght){
		var diff = 	(wndHeight-divHght);
		var topMarginVal = (diff/2);

Sometimes you can center align the DIV vertically by changing the css property “display” to “table” and setting the “vertical-align” to “middle“. But please note that this technique might not work in all the browsers.

 Center align DIV Vertically using CSS

Though there are no straight forward ways or properties to vertically Center align a DIV or a Block element, there are few work around.

One of the ways would be to use the “display:table” property. But hey, you need to set this property to the parent of the DIV you are trying to vertically center align. And the child DIV or the DIV u want to center align can have “display:table-cell” and “vertical-align:middle” properties. Lets take a look at an example.

<style type="text/css">

  display:table-cell; /* Change to inline-block on older versions of IE */


<div class="parent">
    <div class="child">Content goes here</div><!-- Div to be center aligned -->

While this method works good in modern browsers, it might cause a little trouble on older browsers especially older versions of IE. On IE you can set the child DIV’s display as “inline-block“. You may use conditional comments for IE so that it becomes easy for you to target IE separately.

Let us know if you have come across any other way to center align a div.