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

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;

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));

The browser support for CSS Scroll Behavior is pretty good, as it works in the next version of Edge, Chrome and Firefox. You can try it here, jump back to the top. You can also checkout the a full working demo in the link below!

Web Component Essentials

Build reusable UI components with my new Course & E-Book!

Start now!

View Demo Code