WP-Mix

A fresh mix of code snippets and tutorials

Replace JavaScript Smooth Scroll with CSS

In the past, we had to resort to JavaScript to smoothly scroll to on-page target destinations. Fortunately things have evolved and we can now save some extra kilobytes by replacing (relatively) heavy handed JavaScript and jQuery techniques with just a few bytes of CSS.

Tell the browser to smooth scroll to any on-page destinations (i.e., anchor links) with the following code snippet:

html {
	scroll-behavior: smooth;
}

As written, that will apply smooth scroll to all internal links on the page, for example any links that target on-page elements such as:

#some-section
#another-section
#header
#content
#footer

So if the user clicks any links that target # anchors (hash tags), the browser will scroll smoothly to the destination. A real nice effect in some cases.

If you don’t want all internal links to scroll, you can get more specific with the CSS. For example, if you only want the “Return to Top” link to smooth scroll, change the above CSS to this instead:

.return-to-top {
	scroll-behavior: smooth;
}

Browser support is near 100%, with only Internet Explorer not on board. The good news is that this technique gracefully degrades, so anchor links will continue to work on good ol’ IE, just without the fancy scroll effect.

★ Pro Tip:

Digging Into WordPressGA Pro