How to center an element using jQuery

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

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


This can be called using


Where “a” is the element id

Demo can be found here

Leave a Reply

Your email address will not be published.