最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Animate Margins to Auto? - Stack Overflow

programmeradmin2浏览0评论

I'm trying to animate an image so that it centers itself. Here's the code I'd like to use:

$('#myImage').animate({'margin-right': 'auto'});

But when I do that, it's ignored and doesn't change the margin.
Is there a way to animate a margin to auto, or otherwise center an image?

Thanks!

I'm trying to animate an image so that it centers itself. Here's the code I'd like to use:

$('#myImage').animate({'margin-right': 'auto'});

But when I do that, it's ignored and doesn't change the margin.
Is there a way to animate a margin to auto, or otherwise center an image?

Thanks!

Share Improve this question asked Dec 22, 2010 at 16:02 NathanNathan 7,03212 gold badges40 silver badges56 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

As 'auto' isn't a number, jQuery cannot animate it.

If you are okay with taking the image out of the flow of the document, you can set position to absolute or fixed and try:

$('#myImage').animate({'left': '50%', 'margin-left': -$('#myImage').width()/2 });

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

Expanding on Josiah Ruddell's answer. If you guys need your image to keep its flow in the document, use this modified version of Josiah's answer. My image was originally positioned at margin: 0 -1000px, and slides in to the calculated margin left and right. While keeping its flow in the dom the whole time

jQuery.fn.center = function () {
  var margin = ( $(window).width() - this.width() ) / 2;
  this.animate({
    marginLeft: margin, 
    marginRight: margin
  }, function(){
    $(this).css({margin: '0 auto'});
  });
  return this;
} 
发布评论

评论列表(0)

  1. 暂无评论