We love JavaScript, of course. But it's always fun to see what we can achieve with CSS alone - especially when it comes to animations, since CSS animations are often "less heavy" than JavaScript animations.
In this post, I'll show you how to create an infinite scrolling carousel animation with pause on hover effect using only CSS. Here's a preview of what we'll be building:
ABCABC
This tutorial uses & nesting selector syntax, which is a Baseline 2023 feature. Please adjust the code accordingly if you're targeting older browsers.
Since we want the carousel to be infinite, it should be connected end-to-end. Instinctively, we can try to repeat the cards:
<style>
.carousel {
/* ... */
> * {
flex: 0 0 100%;
}
}
/* Group the cards for better structure. */
.group {
display: flex;
gap: 20px;
/* Add padding to the right to create a gap between the last and first card. */
padding-right: 20px;
}
</style>
<div class="carousel">
<div class="group">
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
</div>
<!-- Add `aria-hidden` to hide the duplicated cards from screen readers. -->
<div aria-hidden class="group">
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
</div>
</div>
Check out the result:
ABCABC
Only the first set of cards is visible. If you check the HTML, you'll see that the second set of cards is hidden and follows the first set.
Time to animate the carousel! Since we have two sets of cards connected, we can animate the carousel by transforming the card groups. Here's how:
<style>
.group {
/* ... */
will-change: transform; /* We should be nice to the browser - let it know what we're going to animate. */
animation: scrolling 10s linear infinite;
}
@keyframes scrolling {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
</style>
We still have one last touch to add: pausing the animation when hovering over the carousel. This will give users a chance to see the content more clearly. Since we have two sets of cards, we need to pause both groups when hovering over the carousel:
CSS is powerful, and it's always fun to explore what we can achieve with it. There are also other CSS properties like scroll-snap-type and scroll-snap-align that can help you create an interactive carousel. Happy coding! 🚀