Home Java Javascript - Center a web page vertically

Javascript - Center a web page vertically

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; } else { containerHeight = containerlientHeight; } var lmtHeight; if (lmt.innerWidth) { lmtHeight = lmt.innerHeight; } else { lmtHeight = lmffsetHeight; } var y = Mateil((containerHeight - lmtHeight) / 2); if(y < 0) { y = 0; } lmt.style.position = "relative"; lmt.styleop = y + "px"; } if (document.getElementById) { document.body.style.visibility = 'visible'; } } function addevent(obj,evt,fn,capt){ if(obj.addEventListener) { 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:

Implementation

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

, will be centered.

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

  • Java

LEAVE A REPLY

Please enter your comment!
Please enter your name!