CSS margin-left transition not working

DarkW picture DarkW · Jun 2, 2015 · Viewed 40.1k times · Source

I'm trying to do a transition from the center to left and reduce the height of an image. The height transition is working fine, but the margin just teleports to the left instead of animating.

this is my code:

#logo_img {
    height: 55px;
    width: 55px;
    background-color: red;
    margin-left: auto;
    margin-right: auto;
    display: block;
    transition: all 1s ease-in-out;
}

#logo_img.tiny {
    height:45px;
    margin-left: 0;
}

JS:

$('#logo_img').addClass('tiny');

working example: http://jsfiddle.net/v0w6s3ms/1/

any help?

Answer

Akshay picture Akshay · Jun 2, 2015

You can't animate auto property instead try something like this

$(function() {
  setTimeout(function() {
    $('#logo_img').addClass('tiny');
  }, 1000);
});
#logo_img {
  height: 55px;
  width: 55px;
  background-color: red;
  margin-left: calc(50% - 55px);
  margin-right: auto;
  display: block;
  transition: all 1s ease-in-out;
}
#logo_img.tiny {
  height: 45px;
  margin-left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="logo_img"></section>