Creating a Slide Show with CSS Scroll Snapping
Leveraging a new CSS feature to make a slideshow presentation
Scroll snapping has been a popular website feature for years now. It’s often used to create carousels and image galleries. When implemented poorly, it provides a frustrating user experience. The term scroll hijacking is often used to describe websites that manipulate the default scrollbar experience. However, when done right and not overused, it can provide a pleasant user experience.
Can I use it?
Let’s face it — when discussing new CSS language features, this question always comes up. Scroll Snap is fully implemented in Chrome, Firefox and Safari. An older version of the spec is implemented in (non-chromium) Edge and IE 11. It’ s also supported by IOS and mobile Chrome on Android. So the support is there, it’s up to us as developers to start using it.
Why should we make a web-based slideshow?
As web developers, we are very good at making great looking websites. We have no problems positioning our content using flexbox and CSS Grid. So why bother fighting with Powerpoint or Keynote when we can do it ourselves using HTML and CSS?
Let’s start by making the HTML markup we will need for our slide show deck.
It’s pretty simple.
<div class="slide"><h1>First slide</h1></div>
<div class="slide"><h1>Second slide</h1></div>
<div class="slide"><h1>Third slide</h1></div>
Then we add our CSS.
scroll-snap-type: x mandatory;
What is interesting here are the properties
scroll-snap-align. Since we are creating a slide show, we want our scrolling to be horizontal. That’s why we use
x as the value for
scroll-snap-type. Other options include
block. We could also adjust the strictness of the snapping by changing the strictness to
proximity. The other change we make to our
slide-container is we set
For the slides themselves, we want them to take up 100% of the viewport width and height, so we set
100vw and height to
100vh. We also set the property
start. This makes our snapping occur at the start of the element. We need to set this, as the default value is none, which means no snapping would occur.
Trying it out
Let’s just clean it up a bit, and make it look a bit nicer. I started by modifying the HTML for a slide to look like this.
<img src="image-path" />
The giant panda, also known as panda bear or simply panda, is a bear native to south central China. It is easily recognized by the large, distinctive black patches around its eyes, over the ears, and across its round body.
Next, I made added the following changes to the CSS.
Then I just added a few more slides with different animal pictures and information.
And voila, the final product.
Check out the codepen below to see the full implementation.