CSS Carousel - Animated Hero
This automatically animated Hero component does require dupe HTML, but the animation and looping is all CSS, no JS required.
Demo
Slide 1
Slide 2
Slide 3
Slide 1
Slide 2
Slide 3
HTML
<!-- Requires a wrapper element -->
<div class="css-carousel">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
<!-- Does require dupe content -->
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
</ul>
</div>CSS
/** Requires wrapper element to control overflow **/
.css-carousel {
/* Optionally remove the scrollbar */
scrollbar-width: none;
/* Setup basic Carousel */
width: 100%;
display: flex;
flex-wrap: nowrap;
overflow-inline: auto;
/* Prevent accidental page Back/Forward */
overscroll-behavior-inline: contain;
/* Confine the scrolling direction */
scroll-snap-type: inline mandatory;
/* Be nice to others */
@media (prefers-reduced-motion: no-preference) {
/* Makes the sliding a little smoother */
scroll-behavior: smooth;
}
div {
/* To make this a little more appealing */
aspect-ratio: 2 / 1;
min-width: 100%;
border: 1px solid;
place-content: center;
text-align: center;
/* LIs should always snap and stop */
scroll-snap-stop: always;
/* Be nice to others */
@media (prefers-reduced-motion: no-preference) {
animation: animated-loop__hero 10s ease-in-out infinite;
animation-fill-mode: forwards;
}
}
}
/* Create the animation for the loop effect */
/** Note that iOS (currently) needs the GPU activation from translate3d **/
@keyframes animated-loop__hero {
0% {
transform: translate3d(0, 0, 0);
}
33.333% {
transform: translate3d(-100%, 0, 0);
}
66.666% {
transform: translate3d(-200%, 0, 0);
}
99.999% {
transform: translate3d(-300%, 0, 0);
}
100% {
transform: translate3d(0, 0, 0);
}
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.