I have a list of boxes with a background image that scrolls vertically with:
@keyframes movie {
0% { background-position: 50% 5%; }
50% { background-position: 50% 95%; }
0% { background-position: 50% 5%; }
}
.movie {
animation: movie 50s linear infinite;
}
The "problem" is that in this way all the boxes have the background moving at the same time.
I'd like to have a "random start point" so that each box has a different animation.
For example, one background is moving down while another is moving up.
It is possible with pure CSS? I can't find a simple way neither with Javascript..
The CSS animation-delay property has the following syntax: animation-delay: [time] | initial | inherit; As you can see, there are three possible values: time, initial, and inherit. The first option is [time], which is the number of seconds or milliseconds before the animation starts.
The @keyframes CSS at-rule controls the intermediate steps in a CSS animation sequence by defining styles for keyframes (or waypoints) along the animation sequence. This gives more control over the intermediate steps of the animation sequence than transitions.
You could use jQuery Slide and Math. random(), generating one random number to use as the distance to move and another random number to base your decision on which direction to move in. Save this answer.
Each keyframe describes how the animated element should render at a given time during the animation sequence. Since the timing of the animation is defined in the CSS style that configures the animation, keyframes use a <percentage> to indicate the time during the animation sequence at which they take place.
You can use animation-delay
.
animation-delay: 10s;
Or inside your shorthand:
animation: movie 50s linear 10s infinite;
Maybe easier to handle, with some pseudo-classes:
.movie:nth-of-type(1) {
animation-delay: 10s;
}
.movie:nth-of-type(2) {
animation-delay: 20s;
}
.movie:nth-of-type(3) {
animation-delay: 30s;
}
To elaborate on the suggestion in Chef's answer, the Javascript to randomise the animation delays on a bunch of elements might look something like this:
var elements = document.querySelectorAll('.movie')
var animationDuration = 50000; // in milliseconds
// Set the animationDelay of each element to a random value
// between 0 and animationDuration:
for (var i = 0; i < elements.length; i++) {
var randomDuration = Math.floor(Math.random() * animationDuration);
elements[i].style.animationDelay = randomDuration + 'ms';
}
Of course, you can multiply randomDuration
by -1 if you want to use negative values for animation delay (so some elements start mid-animation rather than having their initial animation delayed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With