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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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;
}
-->
</style>
<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 =  divobj.style.width.replace('px', '');
      //var divHeight =  divobj.style.height.replace('px', '');
      var divLeft = (pageWidth - divWidth) / 2;
      var divTop = (pageHeight - divHeight) / 2;
      //Set Left and top coordinates for the div tag

      divobj.style.left = divLeft + "px";
      divobj.style.top = divTop + "px";
      divobj.innerHTML = "Page Width:"+pageWidth+"<br />Page Height:"+pageHeight;
      divobj.innerHTML += "<br /><br />Div Width:"+divWidth+"<br />Div Height:"+divHeight;
}
</script>
</head>
<body >
<div id="mydiv">
<a onclick="center_align('mydiv')" href="#">Put me at Page Center!</a>
</div>
</body>
</html>

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 =  divobj.style.width.replace('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.

10 comments:

  1. 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

    ReplyDelete
  2. thank you so much for this nice information Article, Digitahanks for sharing your post with us.WEBMETHODS training in bangalore

    ReplyDelete
  3. I have read your blog its very attractive and impressive. I like it your blog.Informatica Training in Bangalore

    ReplyDelete
  4. Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledgez. IMSBI Training in Bangalore

    ReplyDelete
  5. Really i appreciate the effort you made to share the knowledge. The topic here i found was really effective...

    Get Best SAP FICO Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  6. Such a great word which you use in your article and article is amazing knowledge. thank you for sharing it.

    Looking for SAP SD Training in Bangalore, learn from eTechno Soft Solutions SAP SD ADMIN Training on online training and classroom training. Join today!

    ReplyDelete
  7. ts really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.

    aws training in bangalore

    aws courses in bangalore

    aws classes in bangalore

    aws training institute in bangalore

    aws course syllabus

    best aws training

    aws training centers

    ReplyDelete
  8. Very useful and information content has been shared out here, Thanks for sharing...
    Informatica Bangalore

    ReplyDelete

Thanks a lot for your valuable comments :)