How to center an element using jQuery

A simple function can be used to set elements in the center dynamically.

[javascript]
jQuery.fn.center = function () {
this.css(‘position’,’absolute’);
this.css(‘top’, ( $(window).height() – this.height() ) / +$(window).scrollTop() + ‘px’);
this.css(‘left’, ( $(window).width() – this.width() ) / 2+$(window).scrollLeft() + ‘px’);
return this;
}

[/javascript]

This can be called using

[javascript]
$(function(){
$(“#a”).center();
});
[/javascript]

Where “a” is the element id

Demo can be found here

Leave a Reply

Your email address will not be published.