The idea to create an infinite carousel is the following:
terminal+----------------------------+ | Computer screen | | -------------------- | | | | | | ┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐ ┌───┐┌───┐┌───┐ | │ 1 ││ 2 ││ 3 ││ 1 ││ 2 ││ 3 ││ 1 ││ 2 ││ 3 │ ... │ 1 ││ 2 ││ 3 │ | └───┘└───┘└───┘└───┘└───┘└───┘└───┘└───┘└───┘ └───┘└───┘└───┘ | | | | | -------------------- | | | +----------------------------+
You need to repeat the group of elements n times (ideally infinite) to create a loop illusion. Then, move horizontally the whole block.
Let's see the HTML:
HTML<div class = 'Carousel'> <div class = 'Block'>1</div> <div class = 'Block'>2</div> <div class = 'Block'>3</div> <div class = 'Block'>1</div> <div class = 'Block'>2</div> <div class = 'Block'>3</div> <div class = 'Block'>1</div> <div class = 'Block'>2</div> <div class = 'Block'>3</div> <!-- Repeat n times --> <div class = 'Block'>1</div> <div class = 'Block'>2</div> <div class = 'Block'>3</div> </div>
And the CSS:
CSS.Carousel{ animation: carousel 3000s linear infinite; display: flex; flex-wrap: nowrap; width: 100vw; } .Block{ flex-shrink: 0; width: 150px; } @keyframes carousel{ 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(-20000px, 0, 0); } }
If the carousel has a fixed width, you could optimize the previous solution to achieve the same effect with only 2 concatenations.
terminal## Animation starts +----------------------------+ | Computer screen | | -------------------- | | | | | | ┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐ | │ 1 ││ 2 ││ 3 ││ 1 ││ 2 ││ 3 │ | └───┘└───┘└───┘└───┘└───┘└───┘ | | | | | -------------------- | | | +----------------------------+ ## Animation ends +----------------------------+ | Computer screen | | -------------------- | | | | | ┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐ | | │ 1 ││ 2 ││ 3 ││ 1 ││ 2 ││ 3 │ | | └───┘└───┘└───┘└───┘└───┘└───┘ | | | | | | | -------------------- | | | +----------------------------+
Here is the HTML:
HTML<div class = 'Carousel'> <div class = 'Block'>1</div> <div class = 'Block'>2</div> <div class = 'Block'>3</div> <div class = 'Block'>1</div> <div class = 'Block'>2</div> <div class = 'Block'>3</div> </div>
And the CSS:
CSS.Carousel{ animation: carousel 3s linear infinite; display: flex; flex-wrap: nowrap; width: calc(3 * 150px); } .Block{ flex-shrink: 0; width: 150px; } @keyframes carousel{ 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(calc(3 * -150px), 0, 0); } }
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.