Tuesday, May 15, 2012

How to center a div in the middle of the window?

It is very simple. You just have to make a new function like this:

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;
}

Now we can just write:
$(element).center();

2 comments:

  1. That's what I call short but very useful. Thanks for sharing the little tip of adjustments. I look forward to more tutorials you'll be providing.

    ReplyDelete