Animate an object by the width of its parent using css transforms

I am trying to improve animation performance using css transforms to translate the position of an element inside a 100% width wrapper. Thus, he enters the screen on the left side and exits on the right before repeating the animation.

I decided that I could use percentages for this animation. what I find is that the translation is relative to the object you are animating.

So, if you have an object with a width of 100 pixels and you set the animation as follows:

@keyframes moveme { 0% { transform: translate(-100px, 150px) } 100% { transform: translate(100%, 100px) } } 

The object will move 200% of the width of the objects, so 200 pixels.

Is there any fix for moving an object across the width of the container using css conversion in keyframe animations?

Here is my code so far codepen.io/matttunney/pen/dPMQZL

thanks

+6
source share
1 answer

You can use a wrapper around your element, set the width of the wrapper to 100%. and revive it.

Thus, the translation applies to the width of the element, as you declare, but the width of the element corresponds to the width of the container

 .banner { display:block; width:100%; height:300px; background:#0069aa; position:relative; } .moveme, .movewidth { position:absolute; } .movewidth { width:100px; height:100%; background: #edaf02; transform: translate3D(0,0,10px) } .wrapper { width: 100%; animation: moveme 10s linear infinite; } .moveme { background:#003356; width:100px; height:100px; transform: translate3D(0,150px,20px) } @keyframes moveme { 0% { transform: translate(0%, 150px) } 100% { transform: translate(100%, 100px) } } 

demo

As Simon_Weaver points out, it is confusing to have 2 elements with 100% width; it is not clear which one is being proposed as a solution.

Best demo

 .banner { display:block; width:400px; height:300px; background:#0069aa; position:relative; } .moveme, .movewidth { position:absolute; } .movewidth { width:100px; height:100%; background: #edaf02; transform: translate3D(0,0,10px) } .wrapper { width: 100%; -webkit-animation: moveme 1s linear infinite; animation: moveme 1s linear infinite; } .moveme { background:#003356; width:100px; height:100px; transform: translate3D(0,150px,20px) } @keyframes moveme { 0% { transform: translate(0%, 150px) } 100% { transform: translate(100%, 100px) } } @-webkit-keyframes moveme { 0% { transform: translate(0%, 150px) } 100% { transform: translate(100%, 100px) } } 
  <div class="banner"> <div class="movewidth"> </div> <div class="wrapper"> <div class="moveme"> </div> </div> </div> 
+4
source

Source: https://habr.com/ru/post/979613/


All Articles