我正在使用以下 jquery 代码在页面上居中 div,问题是除非我在 css 中为 div 指定高度,否则它不起作用,问题是 div 应该根据里面的内容调整大小. 如果我在 css 中设置 height:auto ,我仍然会遇到问题,但是如果我将 height:300px 例如放在页面上,那么它会将 div 居中。
我在这里有一个问题的 jsfiddle:http: //jsfiddle.net/Vjvyz/
jQuery
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);
HTML
<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 fervour we put into everything we do in the company, and in developing the right organisational 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>
CSS
.container {width:300px; background:#eee; height:300px;}