• support@answerspoint.com

Using jQuery to center a DIV on the screen

616

How do I go about setting a

in the center of the screen using jQuery?

 

1Answer


0
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)

 
  • answered 3 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 3 years ago
  • viewed 616 times
  • active 3 years ago

Hot Questions