Cory Rylan

My name is , Google Developer Expert, Speaker, Software Developer. Building Design Systems and Web Components.

Follow @coryrylan
CSS

CSS Smooth Scroll Behavior

Cory Rylan

- 1 minute

css

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>

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!

View Demo Code   
Twitter Facebook LinkedIn Email
 

No spam. Short occasional updates on Web Development articles, videos, and new courses in your inbox.

Related Posts

CSS

Design System Architecture - Managing CSS Themes

Learn how to use leverage CSS themes to create a flexible and efficient theming system in your design system architecture.

Read Article
CSS

Flow Charts with CSS Anchor Positioning

Learn how to use CSS Anchor Positioning to create flow charts and diagram with just CSS.

Read Article
CSS

Dynamic Contrast Layers with CSS Style Queries

Learn how to create contrasting layers with CSS style queries ensuring your UI is always the right contrast ratio.

Read Article