Why does my transform animation override my original transform?

Viewed 7779

I have three elements, Each of them with its own transform, and I want to animate their translate transform not affecting scale:

.one{
    -webkit-transform: scale(0.5);
}
.two{
    -webkit-transform: scale(0.8);
}
.three{
    -webkit-transform: scale(0.2);
}

@-webkit-keyframes bounce{
    from{
        -webkit-transform: translate3d(0, 0, 0);
    }
    to{
        -webkit-transform: translate3d(100px, 100px, 0);
    }
}
<div class="one">test1</div>
<div class="two">test2</div>
<div class="three">test3</div>

But this transform overrides scale. I could use different keyframes for each element. Or wrap each element and style its parent with scale transform and use one only keyframes to animate it. But this all is kind of tricky. Is there a better solution?

http://jsfiddle.net/422t2/

3 Answers

You’re thinking about the transform property wrong. Each element has one transform property and you reset it with your per-element animations. You need to write an animation like this:

.one{
    transform: scale(0.5);
    animation: bounce 1s ease 1s infinite alternate;
}

.two{
    transform: scale(0.5)
}

@keyframes bounce{
    from{
        transform: scale(0.5) translate3d(0, 0, 0);
    }
    to{
        transform: scale(0.5) translate3d(100px, 100px, 0);
    }
}
<div class="one">test1</div>
<div class="two">test2</div>
<div class="three">test3</div>

This preserves the scale component of your transform while allowing the browser to animate the translation. And in your case, you’d write a new animation for each class, and could drop the original scale declaration in favour of animation-fill: both

The other answers here add the animation to a wrapper div, which is a good solution, and if you mess with the transform-origin properties of all your elements and wrapper you should get a lot of flexibility. With a wrapper it’s easier to handle changing compound transformations, even a wrapper round each element can work out elegantly in some cases.

Related