Back jQuery

Center an element on the screen using jQuery

WRITTEN BY ON 17 Feb 2011
32,928 VIEWS • SHARES
7 comments

This code snippet add a new function called center to the jQuery. Really handy to call the function and apply it to the element you want to center it on screen.

JS - jQuery

This add a function called center to the jQuery.


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

JS - jQuery

This is how you use it


$('#window').center();


Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

7 comments
Yuvraj 12 years ago
Hi,
Dows this work for image as its not working for me.

Thanks
Yuvraj
Reply
Rajesh Das 9 years ago
I am trying to use '$('#window').center();', But it shows error '$(...).center is not a function'. Jquery have no method like center().

So Can anyone suggest?
Reply