CSS Smooth Scrolling
Rik Schennink
Posted on February 14, 2019
Last year, while building the FilePond product page I stumbled upon the scrollIntoView API. It's a handy method to instruct the browser to scroll an element into the viewport.
This article was originally published on my personal blog
The scrollIntoView
API can be instructed to animate the scrolling part by adding the behavior
property on the scrollIntoViewOption
object.
element.scrollIntoView({ behavior: 'smooth' });
I quickly jumped on my JavaScript horse and wrote a tiny script to automatically detect clicks on anchors so the browser would animate the jump towards the anchor target. This jump can be really disorienting, so animating this process would improve the user experience quite a bit.
scrollIntoViewOption currently only works on Firefox and Chrome.
I posted it on Twitter and called it a day.
Then, Hans Spieß points out that this can also be done with CSS, WHAT!?
Turns out there's a scroll-behavior
CSS property that we can set to smooth
, it's literally that literal. It's almost like awesome: yes-please
. We can set the scroll-behavior
property to the container we want to exhibit smooth scroll behavior and we're done.
I created a new demo using only CSS.
Before we go nuts and apply this to all our sites, there are a couple of things we need to keep in mind.
Scroll distance matters
If there is a lot of distance to travel, Firefox will skip content to keep the scroll time-limited, while Chrome has a max velocity and will just take its time to get to the target.
We could use Smart CSS to detect long pages and conditionally apply the smooth scroll style.
Accessibility
People might get motion sickness when watching the animation. To circumvent this you can wrap the CSS property in a prefers-reduced-motion
media query. Unfortunately, Chrome does not support this. Safari supports it, but Safari doesn't support smooth scrolling.
.my-smooth-container {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
.my-smooth-container {
scroll-behavior: auto;
}
}
Conclusion
When deciding on a new functionality we shouldn't reach out to JavaScript immediately. We should do a quick search first to find out if it can be done with CSS as well. The scroll-behavior
property can be a nice UX improvement, do make sure you disable it on very long pages and offer an option to disable it to keep your pages accessible.
Posted on February 14, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.