Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate block back and forth within div continuously with CSS3 keyframes

Tags:

html

css

keyframe

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.

like image 461
Applecot Avatar asked Feb 26 '15 03:02

Applecot


People also ask

Does CSS3 use keyframe animation?

An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want. To use CSS animation, you must first specify some keyframes for the animation.

Which CSS property is used to play animation again and again?

The animation-play-state CSS property sets whether an animation is running or paused.


1 Answers

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

like image 149
ZEE Avatar answered Sep 21 '22 08:09

ZEE