The below code snippet explains how to center an HTML DIV control in the center of Viewport or page using jQuery.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type = "text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></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');
});
</script>
</head>
<body>
<form>
<div id = "dvDemo" style = "border:1px solid red;width:200px;height:100px">
</div>
</form>
</body>
</html>
Explanation:
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.
Demo: