You can only tell once it's been added to the document (that is, you can't tell the expected size and you won't be able to do it server-side).
So, in Javascript, set the visibility to hidden
, add it to the document, check its outerHeight
or with jQuery call $('.window').height()
, reposition as needed, and then change visibility back to visible
.
...or, use this plugin:
jQuery(function($) {
$.fn.vCenter = function(options) {
var empty = {},
defaults = {
allowNegative : false,
relativeToBody : true
},
settings = $.extend(empty, defaults, options)
;
var isVisible = this.is(":visible");
if (!isVisible) {
this.css({visibility : "hidden"}).show();
}
if (settings.relativeToBody && this.offsetParent().get(0).nodeName.toLowerCase() != "body") {
this.appendTo(document.body);
}
var pos = {
sTop : function() {
return window.pageYOffset || $.boxModel && document.documentElement.scrollTop || document.body.scrollTop;
},
wHeight : function() {
if ($.browser.opera || ($.browser.safari && parseInt($.browser.version, 10) > 520)) {
return window.innerHeight - (($(document).height() > window.innerHeight) ? getScrollbarWidth() : 0);
} else if ($.browser.safari) {
return window.innerHeight;
} else {
return $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
}
}
};
return this.each(function(index) {
if (index === 0) {
var $this = $(this),
$w = $(window),
topPos = ($w.height() - $this.height()) / 2 + $w.scrollTop()
;
if (topPos < 0 && !settings.allowNegative) topPos = 0;
$this.css({
position: 'absolute',
marginTop: '0',
top: topPos //pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2)
});
if (!isVisible) {
$this.css({visibility : ""}).hide();
}
}
});
};
$.fn.hCenter = function(options) {
var empty = {},
defaults = {
allowNegative : false,
relativeToBody : true
},
settings = $.extend(empty, defaults, options)
;
if (settings.relativeToBody && this.offsetParent().get(0).nodeName.toLowerCase() != "body") {
this.appendTo(document.body);
}
return this.each(function(index) {
if (index === 0) {
var $this = $(this),
$d = $(document),
leftPos = ($d.width() - $this.width()) / 2 + $d.scrollLeft()
;
if (leftPos < 0 && !settings.allowNegative) leftPos = 0;
$this.css({
position: "absolute",
left: leftPos
});
}
});
};
$.fn.hvCenter = function(options) {
return this.vCenter(options).hCenter(options);
};
});
Usage:
$('.window').hvCenter(); // horizontal and vertical center