The below code snippet explains how to center an HTML DIV control in the center of Viewport or page using jQuery.
<html xmlns="">
    <script type = "text/javascript" src=""></script>
    <script type = "text/javascript">
        $(function () {
            var top = Math.max($(window).height() / 2 - $("#dvDemo")[0].offsetHeight / 2, 0);
            var left = Math.max($(window).width() / 2 - $("#dvDemo")[0].offsetWidth / 2, 0);
            $("#dvDemo").css('top', top + "px");
            $("#dvDemo").css('left', left + "px");
            $("#dvDemo").css('position', 'fixed');
        <div id = "dvDemo" style = "border:1px solid red;width:200px;height:100px">
In the above HTML Markup I have a DIV with ID dvDemo with a fixed height and width which I need to align in the center of page or viewport vertically and horizontally.
To achieve the desired result I first calculate the top and left based on the DIV’s height and width and then set the DIV’s top and left CSS property with the calculated values.
You will notice that I have set the position CSS property as fixed. You can also set it as absolute. Both will give same results but the setting it as fixed will keep it centered even if the page is scrolled.