The full code again:
.gallery {
--d: 6s; /* duration */
display: grid;
overflow: hidden;
-webkit-mask: linear-gradient(90deg,#0000,#000 10% 90%,#0000);
}
.gallery > img {
grid-area: 1/1;
height: 200px;
aspect-ratio: 1.5;
object-fit: cover;
animation: r var(--d) linear infinite;
}
.gallery > img:nth-child(2) {animation-delay: calc(1*var(--d)/-4)}
.gallery > img:nth-child(3) {animation-delay: calc(2*var(--d)/-4)}
.gallery > img:nth-child(4) {animation-delay: calc(3*var(--d)/-4)}
@keyframes r {
75% {transform: translate(-300%)}
75.01% {transform: translate( 100%)}
}
With only a few lines of code, we get an infinite slider that works without duplicating the images.
Using N images
We can still do better and introduce another variable to make the code generic so it can work with any number of images.
For this we will rely on Sass:
$n:5; /* number of images*/
.gallery {
--d: 10s; /* duration */
display: grid;
overflow: hidden;
width: 380px;
-webkit-mask: linear-gradient(90deg,#0000,#000 10% 90%,#0000);
}
.gallery > img {
grid-area: 1/1;
width: 100%;
aspect-ratio: 1.5;
object-fit: cover;
animation: r var(--d) linear infinite;
}
@for $i from 2 to ($n + 1) {
.gallery > img:nth-child(#{$i}) {animation-delay: calc(#{(1 - $i)/$n}*var(--d))}
}
@keyframes r {
#{100*($n - 1)/$n}% {transform: translate((1 - $n)*100%)}
#{100*($n - 1)/$n + .01}% {transform: translate(100%)}
}
When we used 4 images we had to translate by -300% so with N images we need (1 - N)*100%. For the delays, we use a loop to set the value for all the images.
For the keyframes, remember the formulas we used:
T1 + T2 = 100%
T1 = 3*T2
Instead of 3, we will use N - 1 to get
T1 + T2 = 100%
T1 = (N - 1)*T2
Which will give us
T1 = 100% * N/(N - 1)
That’s it! With simple math, we transformed our code into a generic one that can work with any number of images: