Scrolling
Here’s a demo of two great CSS scrolling properties, scroll-behavior
and scroll-snapping
used to create a pure CSS slider.
The buttons are simple anchor tags that link to the id of each slide:
<nav class="slider">
<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>
<a href="#four">four</a>
<a href="#five">five</a>
<a href="#six">six</a>
</nav>
All the slider is within a container with the following CSS:
.sliderwrapper {
width: 100%;
height: 550px;
scroll-snap-type: y mandatory;
scroll-behavior: smooth;
display: grid;
grid-template-columns: repeat(6, 100%);
grid-auto-flow: column;
overflow-x: scroll;
overflow-y: hidden;
}
The child elements, the slides, use the following CSS:
.sliderwrapper > section {
min-width: 100%;
display: grid;
place-content: center;
scroll-snap-align: start;
background-color: #238;
height: 550px;
padding: 1em;
}
Scroll behavior
This is a great addition that can be implemented with a single line of code:
html {
scroll-behavior: smooth;
}
What it does: this is a UX enhancement that works when you click a link to somewhere else on the same page. Usually you are taken there instantly and it’s easy to lose a sense of where you are on the page or even whether you’re still on the same page. With scroll-behavior
set to smooth
the page scrolls up, down or even sideways to the part of the page linked to.
Typical use cases are a back to top link, pages that have a table of contents, or pages with areas out of the viewport.
GOTCHA’s:
- For a full page effect add this to the
<html>
element NOT the<body>
. - For UK devs note the US spelling of
behavior
Scroll snapping
This is really handy for touch screens but can be awkward for mouse based devices.
What it does: On pages that have clear content or section boundaries when you scroll it will snap to predefined points.
This has gone through several iterations but the final code is implemented on all of the main browsers.
You add two lines of code, one to the containing element of the sections (if the whole page then the html
element) and one for each section or child element.
The first sets the axis, x or y, where this is applied. The second, mandatory
means the scrolling is strict. An alternative is proximity
which means the snapping only works when
.container {
scroll-snap-type: y mandatory;
}
section {
scroll-snap-align: start;
}
Links
- See also Javascript sliders will kill your website performance about JS sliders vs pure CSS