Using jQuery to center a DIV on the screen

Craig picture Craig · Oct 17, 2008 · Viewed 515.9k times · Source

How do I go about setting a <div> in the center of the screen using jQuery?

Answer

Tony L. picture Tony L. · Oct 17, 2008

I like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)