I am trying to center a div
in the middle of the window using CSS and then slide it to the left using the jQuery's animate
function. The CSS and animate function are working, however when the animation starts, the div
jumps to the right and then animates from that location.
I have created a fiddle to demonstrate the problem. Notice that the red and yellow boxes should start at the same centered location, but the red box starts animating further right in the window.
http://jsfiddle.net/Zeaklous/XMKCc/2/
To prove to myself that animate works correctly without a CSS centered div, I included two boxes centered using javascript in the same fiddle. The pink box animates from the position that I would expect (directly over the purple one).
Is there anything I can do to get the CSS centered div working correctly with animate?
Code below
.centeredByCSS {
left:0;
right:0;
margin:0 auto;
width:50px;
height:50px;
position:absolute;
}
.centeredByJS {
width:50px;
height:50px;
position:absolute;
top:75px;
}
.yellow {
background:yellow;
}
.red {
background:red;
}
.purple {
background:purple;
}
.pink {
background:pink;
}
<div id="box1" class="centeredByCSS red">TEST1
</div>
<div id="box2" class="centeredByCSS yellow">TEST2
</div>
<div id="box3" class="centeredByJS purple">TEST3
</div>
<div id="box4" class="centeredByJS pink">TEST4
</div>
$(function(){
//manually center the purple and pink boxes
var location=(window.innerWidth/2)-parseInt($("#box3").css("width"))/2;
$("#box3").css("left", location);
$("#box4").css("left", location);
// now animate two of the boxes 100 pixels left
$("#box1").animate({left: "-100"}, 10000);
$("#box4").animate({left: "-100"}, 10000);
})