Tip #17: Use the scroll-behavior property to set smooth scrolling

  • — Frontend

  • — 1 min. read

  • — 2/20/2023

Back in the old days, I used to use a jQuery script for adding smooth-scrolling to anchors on my websites.

Nowadays, we have a native CSS property that can do that for us (hooray for less JS 🎉).

It's called scroll-behavior and it lets us determine how scrolling should behave when you click on an internal link that uses hash-routing (an a tag with a # in the href).

To enable global smooth scrolling on your website, simply set the scroll-behavior property on the html tag using a global selector:

html{
	scroll-behavior: smooth;
}

If you're using TailwindCSS, you can set this on the html tag with the following utility:

<html class="scroll-smooth">
	...
</html>

That's it, you now have smooth scrolling to anchor enabled on your website.

Check it out:

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!