I am trying to create an image carousel using CSS where each image appears for four seconds, then cross fades to the next image. I want to include three images that loop.
I found code on another post that seemed close to what I needed, but it was for five images. I thought it would be easy to edit it to just feature three, but I’m not familiar enough with animation timing in CSS and made a mess of it. Now it shows the three images but doesn’t show each long enough, and the fade-out / fade-in animations aren’t overlapping, leaving a gap between each image.
.crossfade>figure {
animation: imageAnimation 12s linear infinite 0s;
backface-visibility: hidden;
background-size: cover;
background-position: center center;
color: transparent;
height: 100%;
left: 0px;
opacity: 0;
position: absolute;
top: 0px;
width: 100%;
z-index: 0;
}
.crossfade {
height: 450px;
width: 100%;
}
.crossfade>figure:nth-child(1) {
background-image: url('img1.jpg');
}
.crossfade>figure:nth-child(2) {
animation-delay: 4s;
background-image: url('img2.jpg');
}
.crossfade>figure:nth-child(3) {
animation-delay: 8s;
background-image: url('img3.jpg');
}
@keyframes imageAnimation {
0% {
animation-timing-function: ease-in;
opacity: 0;
}
8% {
animation-timing-function: ease-out;
opacity: 1;
}
17% {
opacity: 1
}
25% {
opacity: 0
}
100% {
opacity: 0
}
}
<div class="crossfade">
<figure></figure>
<figure></figure>
<figure></figure>
</div>
2
Answers
You need to update the percentages. Something like this:
It looks like a case of just tweaking the timing for
animation
in the.crossfade>figure
selector, as well as theanimation-delay
in each image.Here’s a snippet below, it seems like 2s per image seems to be enough. With an additional 2s for the overall loop.
Hence:
animation: imageAnimation 8s linear infinite 0s;
Additionally, I’ve gone a step further here, if you were generating the images with JavaScript (let’s say you were getting the images from an endpoint). You could use a custom variable
var(--n)
to specifiy the delay like so:This would still give you the number same delay time per image.
If you went even further and had a variable number of images returned from an endpoint.
You could calculate (on
.crossfade>figure
)animation-duration: calc(calc(--l * 2s) + 2s)
where--l
were the number of images to cycle through.See the snippet above to see how
--n
were passed in, and you could apply the same technique to pass a value for--l
.