DEV Community

Nick Frostbutter
Nick Frostbutter

Posted on • Originally published at frostbutter.com on

Add CSS Scroll Animation and Smooth Scrolling

Add CSS Scroll Animation and Smooth Scrolling

The basic way to add smooth scroll animation is using anchors/indexes on your website. Those are the hashtag urls that you can set inside of a link. By default, if someone clicks on of the link their browser will jerk them down to the location of the anchor/id on the page. No so pretty looking. And certainly not a great user experience.

So, how to add the smooth scroll animation you ask?

  • add the anchor link on your page: <a href="#my_link">
  • create the anchor endpoint on the page element: <div id="my_link">
  • add the CSS scroll animation property, aka scroll-behavior
  • enjoy

Add the anchor for smooth scrolling

Assuming you have your website already setup, find whichever link you want to use as your action. Simply assign the href parameter with a hashtag ("#") link of the id the page element to stop scrolling at.



<a href="#myelement">click here to scroll to "myelement"</a>


Enter fullscreen mode Exit fullscreen mode

Create the smooth scroll endpoint element

Next, assign an "id" attribute to the element you want your smooth scroll to stop at. Make sure you give it the exact same name as previously used in the anchor tag. But without the "#" in the id value.



<div class="whatever" id="myelement"></div>


Enter fullscreen mode Exit fullscreen mode

Add CSS scroll animation with "scroll-behavior"

With your page's anchor and endpoint all setup on your website, you can add the smooth scrolling effect by adding this single line into your main CSS file for your website:



html{
  scroll-behavior: smooth;
}


Enter fullscreen mode Exit fullscreen mode

Note: It is important to add the scroll-behavior style on to the html tag so your entire website will have the smooth scrolling effect.

Some people, including myself, have tried to set the smooth scrolling on the body tag. But that does not work for some reason.

Once you save your changes, and reload the CSS into the browser, your snazzy new smooth scrolling will be in effect.

CSS scroll animation on old browsers?

The downside of this UX tip, is that the CSS scroll animation does not work in older browsers. But anyone using any reasonable modern browser should be fine. And worst case, they won't get the added UX boost. But let's be honest, if they are using an older browser (cough internet explorer cough) then they already make poor life decisions. And obviously not looking for the best user experience on the web. Right?

web browser support for css smooth scrolling

The good news is that browser support for the CSS scroll-behavior property has been around for a bit. So that's a plus :)


This article on css scroll animation was originally posted to my personal site at frostbutter.com

Top comments (0)