DEV Community

Cory Rylan
Cory Rylan

Posted on • Originally published at coryrylan.com

CSS Smooth Scroll Behavior

I recently wanted to add a smooth scroll effect on one of my websites and went searching for a JavaScript plugin to achieve it. To my surprise a newer CSS Scroll Behavior API is available in many browsers! With the CSS Scroll Behavior API we can link to inner parts of a HTML page and have the browser scroll to the part of the page instead of immediately jumping to it. I thought this was pretty cool so I wanted to write up a little demo of how it works.

In the past if we wanted to have a smooth scroll to a certain part of the page we would have to use JavaScript to accomplish this. Now with CSS Scroll Behavior we can do it with just a single line of CSS. Using a link I can link to inner parts of my HTML page.

<a href="#some-content">jump to some content</a>

...

<p id="some-content">
  some content
</p>
Enter fullscreen mode Exit fullscreen mode

With this little bit of HTML the user can click the link and have the page jump to the some-content paragraph below. This jumping effect can be a helpful shortcut but also jarring to suddenly move to a completely different part of the page. To make this a better experience we can add the following CSS:

html {
  scroll-behavior: smooth;
}
Enter fullscreen mode Exit fullscreen mode

Now when we click the link, the browser will scroll to the content and not immediately jump to that part of the page. Because the smooth scroll behavior is applied via CSS we can manipulate the scroll position with JavaScript and still get the same nice smooth scroll effect.

const button = document.querySelector('button');
button.addEventListener('click', () => window.scrollTo(0, 1400));
Enter fullscreen mode Exit fullscreen mode

The browser support for CSS Scroll Behavior is pretty good, as it works in the next version of Edge, Chrome and Firefox. You can also checkout the a full working demo

Top comments (0)