Animate block back and forth within div continuously with CSS3 keyframes

Applecot picture Applecot · Feb 26, 2015 · Viewed 7.6k times · Source

JSFiddle

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;} }

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 Stack Overflow question 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.

Any help would be appreciated.

Answer

ZEE picture ZEE · Feb 26, 2015

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 sweets your need

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