Reputation: 6296
I have a simple div
element and I use CSS animations to create a smooth layout:
div{
-webkit-transition: all 1s ease-in-out;
-ms-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
Although is quite simple to animate the element using pixel specific ratios http://jsfiddle.net/yBJ42/1/
it fails when the element is center with margin:0 auto
Is there any way to fix that behavior? Unfortunately I can't use absolute positioned elements as the main container in my layout uses CSS calc in order to calculate it's width and I want to keep margin-right:0
as a sidebar is revealed.
Furthermore calculating and adapting containers width and margin using JavaScript is not the my preferable way of handling this situation.
Thanks in advance.
Upvotes: 0
Views: 1918
Reputation: 7207
this is the jQuery version of what you want: DEMO
var centerMargin=($(window).width()/2)-($('div').width()/2)+'px';
$('div').css('margin-left',centerMargin);
var toggled=false;
$(".animate").click(function(){
if(!toggled){
$('div').animate({marginLeft:'0px'},1000);
toggled=true;
}
else{
$('div').animate({marginLeft:centerMargin},1000);
toggled=false;
}
});
Upvotes: 1
Reputation: 4159
The transform suggestion is a solid solution (see Mike Vranchx's answer).
However, if you absolutely must use margin: auto, than the only way to animate it is to use a nested div. The outer div handles the centering, while animation is handled on the inner div.
<div style="margin: 0 auto; position: relative;">
<div>Content</div>
</div>
Upvotes: 0
Reputation: 76
You can't do this to/from properties like auto, inherit etc. You need to set explicit values in px, percentage, etc.
Upvotes: 0
Reputation: 13
Unfortunately you can not animate properties between 2 non numeric values.
Upvotes: 0
Reputation: 5577
What about applying CSS transformations? You can use transform: translateX
to move your element on the X-axis without impacting your margin: 0 auto
For example, move your element 100% to the left of the current position. (100% is equal to the width of the transformed element)
-ms-transform: translateX(-100%)
-webkit-transform: translateX(-100%)
-moz-transform: translateX(-100%)
transform: translateX(-100%)
Upvotes: 0