DEV Community

Cover image for #LearnedToday: Slider in pure CSS
Daniel Zotti
Daniel Zotti

Posted on

#LearnedToday: Slider in pure CSS

🏞️ Do you remember when you had to use heavy JS libraries to create image slideshows?

💪 Those days are gone! You can do it in pure CSS now! (experimental in Chrome, Edge and Opera)

Main concepts

  • Scroll timeline: define a name and a direction for the scrollable element on which the shorthand CSS scroll-timeline property is applied.
  • Animation Timeline: The animation-timeline CSS property specifies the timeline (defined by the scroll-timeline property) that is used to control the progress of a CSS animation.
  • Timeline scope: The timeline-scope CSS property modifies the scope of a named animation timeline.
  • Animation range: The animation-range CSS shorthand property is used to set the start and end of an animation's attachment range along its timeline, i.e. where along the timeline an animation will start and end.

The idea

  • Associate an horizontal (x axis) scroll timeline to the element that contains the slides (.slider__entries) using the scroll-timeline property (it's a sort of event listener of the scroll event for CSS)
.slider__entries {
  scroll-timeline-name: --carousel;
  scroll-timeline-axis: x; // horizontal
}
Enter fullscreen mode Exit fullscreen mode
  • Raise the scope of the timeline from the child (.slider__entries) to the parent (.slider) using the timeline-scope property
.slider {
  timeline-scope: --carousel;
}
Enter fullscreen mode Exit fullscreen mode
  • Associate the scroll animation to the single "dot" in order to highlight the correct "dot"
@keyframes color-bullet {
  from,
  to {
    background: var(--dot-color--active);
  }
}
.dot a {
  animation: color-bullet linear;
  animation-timeline: --carousel;
  animation-range: calc((var(--i) - 1) / 5 * 100%) calc(var(--i) / 5 * 100.01%); // NB: 5 is because we have 5 images in the example!
}
Enter fullscreen mode Exit fullscreen mode
  • Adding a "snap" effect during the scroll and hide the scrollbar
.slider__entries {
  scroll-snap-type: x mandatory; // horizontal
  scrollbar-width: none; // hide scrollbar
  scroll-behavior: smooth; // scroll smoothly
}
Enter fullscreen mode Exit fullscreen mode
  • Adding the slide switch when clicking on the button
<!-- DOT: --> 
<a href="#slide_01"></a>

<!-- SLIDE: -->
<a name="slide_01"><img src="..." /></a>
Enter fullscreen mode Exit fullscreen mode

Demo

I created as usual a working demo.

Top comments (0)