You cannot animate an auto
property. To properly animate the element to the center of the screen you will need to position it absolutely
(or other) and then calculate the screen size, element size, and scroll position. Here is a another SO answer on something similar. Here is the Fiddle
jQuery.fn.center = function () {
this.css("position","absolute");
var top = ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px",
left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
this.animate({top: top, left: left});
return this;
}
Alternatively if you only want the horizontal alignment you can remove the top from the animate function. And if you really want to get creative you can remove the position:absolute
, and reposition margin:auto
after the animation in case of screen resizing. See another fiddle.
jQuery.fn.center = function () {
this.css("position","absolute");
var left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
this.animate({left: left}, function(){
$(this).css({position: 'static', margin: '0 auto'});
});
return this;
}
$('#selector').center();