How to create Infinite Horizontal Scroll and Hover-Pause with Pure CSS
Have you ever wanted to add an engaging horizontal scroll effect to your website? Combining CSS animations and hover states can bring your content to life. Let’s explore how to achieve an infinite horizontal scroll with a pause-on-hover feature using simple HTML and CSS.
The common problems I’ve seen people struggle with are
1. The horizontal scroll breaks after it reaches the end of the image list.
2. The scroll isn’t smooth after displaying the first image in a new loop.
3. There’s too much space left inside the scroll container before starting a new loop.
You can solve these problems following this article.
Let’s take a look how HTML looks like.
To resolve these issues, duplicate the child element adjacent to the initial child element. Surprisingly simple, right? But how does this solution work?
CSS Magic Unveiled
The CSS file defines styles for elements, including setting up a flexible layout and defining animations. The key lies in the @keyframes
rule, creating a continuous movement effect by animating the left
property from 100%
to -100%
, achieving the horizontal scroll illusion.
The animation-delay
property is used to introduce a delay before the animation starts on elements with the class .carousel-primary
Let's break it down:
animation: scroll-horizontal 20s linear infinite;
: This line specifies the animation applied to.carousel-secondary
. It uses thescroll-horizontal
animation, which is initially set to move the elements horizontally over 20 seconds in a linear fashion, creating the infinite horizontal scroll effect.animation-delay: 10s;
: This property introduces a delay of 10 seconds before the animation starts for elements with the.carousel-secondary
class. Essentially, this delay allows the animation to begin after a specified time interval.
Implementing Hover-Pause with CSS Selectors
Here’s the fascinating part: without any JavaScript intervention, we’re utilizing CSS selectors to introduce hover functionality. When users hover over .carousel-primary
, both .carousel-primary
and .carousel-secondary
pause their animations. Additionally, hovering over the scroll container itself halts the animation on .carousel-primary
unless the user hovers directly over .carousel-primary
.
Here’s the link to the full source code. Feel free to utilize or share it as needed.
Final Thoughts
Crafting an infinitely scrolling image carousel with hover-pause functionality using only HTML and CSS exemplifies the flexibility and creativity these technologies offer. This approach provides an accessible way to enhance user experience without the need for JavaScript libraries or complex scripts.
Happy Coding! 😊