BeWebmaster

Centering content on a page using javascript

Ad

<script type="text/javascript">
  <!--
  function getWindowHeight() {
   var windowHeight = 0;
   if (typeof(window.innerHeight) == 'number') {
    windowHeight = window.innerHeight;
   }
   else {
    if (document.documentElement && document.documentElement.clientHeight) {
     windowHeight = document.documentElement.clientHeight;
    }
    else {
     if (document.body && document.body.clientHeight) {
      windowHeight = document.body.clientHeight;
     }
    }
   }
   return windowHeight;
  }
  function setContent(id) {
   if (document.getElementById) {
    var windowHeight = getWindowHeight();
    if (windowHeight > 0) {
     var contentElement = document.getElementById(id);
     var contentHeight = contentElement.offsetHeight;
     if (windowHeight - contentHeight > 0) {
      contentElement.style.position = 'relative';
      contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
     }
     else {
      contentElement.style.position = 'static';
     }
    }
   }
  }

  //set the parameter of the setContent() function to the ID of the element you want centereded on the page. Usually #wrapper.
  window.onload = function() {
   setContent('wrapper');
  }
  window.onresize = function() {
   setContent('wrapper');
  }
  //-->
  </script>