Here's an extension which I came across and modified slightly. Looking at it now, I think it's actually a bit messy and could use a clean up (there's some unused variables I think)
$.fn.vCenter = function(options) {
var pos = {
sTop : function() {
return window.pageYOffset || $.boxModel && document.documentElement.scrollTop || document.body.scrollTop;
},
wHeight : function() {
if ($.browser.opera || ($.browser.safari && parseInt($.browser.version) > 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 && (options == undefined || !options.allowNegative)) topPos = 0;
$this.css({
position: 'absolute',
marginTop: '0',
top: topPos //pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2)
});
}
});
};
$.fn.hCenter = function(options) {
return this.each(function(index) {
if (index == 0) {
var $this = $(this),
$d = $(document),
leftPos = ($d.width() - $this.width()) / 2 + $d.scrollLeft()
;
if (leftPos < 0 && (options == undefined || !options.allowNegative)) leftPos = 0;
$this.css({
position: "absolute",
left: leftPos
});
}
});
};
$.fn.hvCenter = function(options) {
return this.vCenter(options).hCenter(options);
};
Usage:
$('#verticalCenter').vCenter();
$('#horizontalCenter').hCenter();
$('#bothCentered').hvCenter();