Center Align HTML DIV in Viewport of browser

Last Reply on Jun 25, 2012 09:55 AM By Mudassar

Posted on Jun 25, 2012 08:39 AM

hi i am making a web page in which on the centre of the screen there is a div whose property is position:absolute, top:100px; left:200px;

if the resolution the position of the div also  changes

and if i run it on another desktop the position changes wt should i do.

Posted on Jun 25, 2012 09:55 AM

using JavaScript

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type = "text/javascript">
        window.onload = function () {
            var windowHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
            var windowWidth = Math.max(document.body.clientWidth, document.documentElement.clientWidth);
            var demo = document.getElementById("dvDemo");
            var top = Math.max(windowHeight / 2 - demo.offsetHeight / 2, 0);
            var left = Math.max(windowWidth / 2 - demo.offsetWidth / 2, 0);
            demo.style.top = top + "px";
            demo.style.left = left + "px";
        };
    </script>
</head>
<body>
    <form>
        <div id = "dvDemo" style = "border:1px solid red;width:200px;height:100px;position:absolute">
        </div>
    </form>
</body>
</html>

Demo