Looping images and icons infinitely using CSS only
Dominik Rüttiger3 min read
Source: Photos from Unsplash
I was looking for a CSS-only infinite carousel that was easy to use, easy to
understand and can serve a variable number of images. It should not depend on
SAAS or other tools and work for any type of content.
And here it is! Let’s go through a plain HTML example and integrate it into an
Astro component.
CSS-only infinite carousel
The HTML is pretty straightforward: Two wrapping divs containing a list of
images (or whatever you want to loop over). We duplicate the list for a seamless
loop.
The .slidesCSS rule lays out all the images in a row using flex and
adds a custom animation. Thanks to width: max-content, we can simply move them
by -50%. No need for pixel-based calculations.
The carousel stops when you move the mouse over it and a mask is applied. If you
don’t need this, just remove &:hover and -webkit-mask.
Astro component
For the Astro version, let’s add some image optimizations to make your
Lighthouse audits fireworks!
We make each image take up 50 % of the screen for small displays up to a maximum
of 300 pixels. Loading images eagerly helps to avoid glitches in some browsers.
Images are also cropped to fit a 3:2 aspect ratio.