Code Snippet > JS - jQuery

Center an element on the screen using jQuery

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();



Source: http://stackoverflow.com/questions/210717/what-is-the-best-way-to-center-a-div-on-the-screen-using-jquery



Show Some Love, Spread This Post!

2 comments

Paul Sayre Mon, 21st February 2011 Works well in the base case, but if there is a positioned parent, then this don't quite work. If you were to change it to position fixed, then it would work just fine (except IE6, I think). I have a quick test case.

http://jsfiddle.net/JzQCT/1/
Reply
Eric Schrader Fri, 18th February 2011 Thanks!

Is there any cross browser compatibility issues with window.height/width? I remember running into an issue where I had to toggle between body or window width, not sure if it applies to other cases. Maybe my page had a large horizontal scroll for the content and I a remembering wrong (happens).
Reply

Leave a comment

Have something to say? Drop a comment! No HTML tags are allowed in the comment textfield.

Advertisement