Ask a question »

Javascript - Center a web page vertically

May 2016

How to center a web page vertically; its almost impossible to achieve this with CSS. The most practical solution is to use JavaScript.

The .js file

Copy/paste the following script in a file named for example: center.js

function align()      

 var lmt = document.getElementById('center);      
 var container = document.documentElement;      

 if(lmt && container)      
     var containerHeight;      
     if (container.innerWidth)      
            containerHeight = container.innerHeight;      
            containerHeight = container.clientHeight;      
     var lmtHeight;      
     if (lmt.innerWidth)      
            lmtHeight = lmt.innerHeight;      
            lmtHeight = lmt.offsetHeight;      
  var y = Math.ceil((containerHeight - lmtHeight) / 2);      
  if(y < 0)      
   y = 0;      
  } = "relative"; = y + "px";      
 if (document.getElementById)      
 { = 'visible';      


function addevent(obj,evt,fn,capt){      
  obj.addEventListener(evt, fn, capt);      
  return true;      
 else if(obj.attachEvent)      
  obj.attachEvent('on'+evt, fn);      
  return true;      
 else return false;      

if (document.getElementById && document.getElementsByTagName)      
 addevent(window, 'load', align, false);      
 addevent(window, 'resize', align, false);      

The .html file

For your page to be centered, you must call the .js file.
The page will be displayed as such:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">      
<html lang="en" xmlns="" xml:lang="en">      
  <!-- [...] -->      
  <script type="text/javascript" src="center.js"></script>      
  <div id="centering">      

  <!Put the code of your webpage here. It will be centered -->      


The align() function defined in the .js file will retrieve the content that should be centered. In this example, the item having the ID [id = "center"] will be centered.

var lmt = document.getElementById('center ');

The same goes for the .html page, the contents found between the <div id="center"></div>, will be centered.

Note: this code will only work only if the users has Javascript enabled in their browser.

For unlimited offline reading, you can download this article for free in PDF format:

See also

In the same category

Original article published by gryzzly. Translated by jak58. - Latest update by deri58
This document entitled « Javascript - Center a web page vertically » from CCM ( is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.