Sunday, March 25, 2012

How to center a Div on the screen using JQuery

Centering a Div on the screen (both horizontally & vertically) is truly painful when depending only on CSS, So I'm trying here to make this functionality using JQuery,

first: add the 'center' function to JQuery :
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) +
        $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) +
        $(window).scrollLeft() + "px");
    return this;
}

second: use this function wherever you want:
$('#id').center();

and that is it :)


you can try this code here http://jsfiddle.net/DerekL/GbDw9/