Quantcast
Viewing all articles
Browse latest Browse all 8

(SOLVED) How to center div horizontally and vertically using jQuery

How to center a div horizontally and vertically, no matter if the browser screen is resized?

It is very easy with jQuery…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 	<meta http-equiv="Content-Language" content="es" />
 	<title>Center div horizontally and vertically</title>
 	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script type="text/javascript">
		jQuery.fn.center = function () {
    		  this.css("position","absolute");
    		  this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
    		  this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
    		return this;
		}
		$(window).load(function(){  
			$("#container").center();
		});
		$(window).resize(function(){
			$("#container").center();
		});
	</script>
</head>
<body>	
<div id="container">
	<span>Some content here</span>
</div>
</body>
</html>

Viewing all articles
Browse latest Browse all 8

Trending Articles