htmlcsskeyframe

Animate block back and forth within div continuously with CSS3 keyframes


I'm trying to animate a span that moves back and forth enclosed within a div using CSS3 keyframes. Ideally, I'd like the keyframes to look something like this:

@-webkit-keyframes backandforth {
     0% {text-align:left;} 50%{text-align:right;} 100%{text-align:left;}
}

Demo in JSFiddle

But since it's not possible to animate text-align, I've been searching for an alternative property that can be animated to reach the desired positioning. That's where I'm stuck at.

I tried setting the left property to 100% midway through the animation, but that ended up pushing the span off the div. I also tried animating the float property, but that didn't work.

Then I saw this question on moving text from left to right and tried the JSFiddle from the top answer. While it looks like the solution, it unfortunately did not work for me since I want my animation to move continuously at ease, and for the last few seconds of that animation, the span stalls.


Solution

  • CSS Solution

    you can play around the left position when the animation is at 50% like so :

    because when you put it left: 100% it depend on the left corner of the span this is why it will go out the container div

    @-webkit-keyframes backandforth {0%{left:0;} 50%{left:58%;} 100%{left:0;}}
    

    Live Demo

    I hope this fits your needs

    JavaScript solution

    var thisis = document.getElementById("wrapper");
    var tyty = document.getElementById("move");
    var witth = tyty.offsetWidth;
    
    thisis.style.paddingRight = witth +"px";
    

    Live Demo

    with this JS whatever you change the text it will still in the container div