Monday, June 1, 2009

Center align Div tags horizontally and vertically at Page center using JavaScript

It is easy to horizontally center align div tags on a page by using fixed width and auto left & right margins, but there is no efficient CSS technique which aligns the div tag at vertical center of the page. Though you can use CSS properties like display:table-cell combined with vertical-align:middle to align it roughly at the vertical center but it isn’t always accurate and scalable for div tags with different sizes.

My technique utilizes JavaScript functionalities to change CSS properties on the fly for aligning the Div tag at the page center based upon the current window size. Left and Top coordinates for the div tag are calculated on the fly based upon the window and div tag size. The JavaScript function reads the CSS properties for the div tag from the Stylesheet or inline styles and calculated the coordinates respectively.

Horizonally and Vertically Center Aligned Div Tag

Here is the complete HTML/JavaScript Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Center Aligned div</title>
<style type="text/css">
#mydiv {
      background-color: #CCC;
      height: 200px;
      width: 400px;
      position: absolute;
      padding: 10px;
<script language="javascript">
function center_align(id){
      //Calculate Page width and height

      var pageWidth = window.innerWidth;
      var pageHeight = window.innerHeight;
      if (typeof pageWidth != "number"){
      if (document.compatMode == "CSS1Compat"){
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
      } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
      var divobj = document.getElementById(id);
      //For CSS StyleSheet use:
      if (navigator.appName=="Microsoft Internet Explorer")
      computedStyle = divobj.currentStyle;
      else computedStyle = document.defaultView.getComputedStyle(divobj, null);
      //Get Div width and height from StyleSheet
var divWidth = computedStyle.width.replace('px', '');

      var divHeight = computedStyle.height.replace('px', '');
      //For Inline styling use:
      //var divWidth ='px', '');
      //var divHeight ='px', '');
      var divLeft = (pageWidth - divWidth) / 2;
      var divTop = (pageHeight - divHeight) / 2;
      //Set Left and top coordinates for the div tag = divLeft + "px"; = divTop + "px";
      divobj.innerHTML = "Page Width:"+pageWidth+"<br />Page Height:"+pageHeight;
      divobj.innerHTML += "<br /><br />Div Width:"+divWidth+"<br />Div Height:"+divHeight;
<body >
<div id="mydiv">
<a onclick="center_align('mydiv')" href="#">Put me at Page Center!</a>

If you are using inline styling for the div tag as follows:
<div id="mydiv" style="width: 400px; height: 200px; background-color: #CCC; position: absolute; padding: 10px;">
You can just use the var divWidth ='px', ''); method to retrieve the width and height of the div tag, instead of using the computedStyle object.

You can also use the center_align() function with onload() event inside body tag to automatically align it at page center when the page loads.


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

  2. mytectra placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance.

  3. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

  4. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage
    contribution from other ones on this subject while our own child is truly discovering a great deal.
    Have fun with the remaining portion of the year.
    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training


Thanks a lot for your valuable comments :)