Trying to center a div on the page using jQuery has proven to be a bit tricky. It seems that without specifying a height for the div in the CSS, the centering doesn't work as expected. The challenge lies in the fact that the div is meant to resize based on the content inside it. Even setting height:auto in the CSS doesn't solve the issue. However, assigning a specific height, like height:300px, does the trick.
To better illustrate the problem, I have created a JSFiddle: http://jsfiddle.net/Vjvyz/
Check out the jQuery code below:
var positionContent = function () {
var width = $(window).width(); // the window width
var height = $(window).height(); // the window height
var containerwidth = $('.container').outerWidth(); // the container div width
var containerheight = $('.container').outerHeight(); // the container div height
if ((width >= containerwidth) && (height >= containerheight)){
$('.container').css({position:'absolute',
left: ($(window).width() - $('.container').outerWidth())/2,
top: ($(window).height() - $('.container').outerHeight())/2 });
}
};
//Call this when the window first loads
$(document).ready(positionContent);
//Call this whenever the window resizes.
$(window).bind('resize', positionContent);
See the HTML structure:
<div class="container"></div>
<div class="container">
<div class="logo"></div>
<div class="menucontainer"></div>
<div class="content">
<p>Passion stands for the enthusiasm and fervor we put into everything we do in the company, and in developing the right organizational mix to help others in every possible way<br />
we want every guest to experience that passion for life by having the most relaxing, blissful and luxurious stay possible, a time filled with personal discovery, recovery and spiritual fulfillment.</p>
<p>We want every employee to taste that passion for life by growing in confidence and skills, and feeling part of a close-knit global family.</p>
</div>
</div>
And the CSS styling:
.container {width:300px; background:#eee; height:300px;}