You ever wonder how to add smooth scrolling to links a website? Well I am going to show you how I add them to my websites using only Tailwind CSS. No Javascript required! I am going to assume you have Tailwind CSS installed in your project, so we will skip that part. However, if you need to help on how to install Tailwind CSS, you can check out the official installation guide.
The Javascript Way
The way I normally add smooth scrolling to a website is by writing something simple like this:
const scrollTop = () => window.scrollTo({ top: 0, behavior: 'smooth' })
Then I would just simply call this function when needed with a click event (I'm using React):
<button onClick={scrollTop}>Scroll to Top</button>
It's really easy to do with Javascript but what if you don't want to use Javascript? Well lucky for us, Tailwind CSS has a super simple way to add smooth scrolling to your website without writing any Javascript.
The Tailwind CSS Way
Simple add scroll-smooth to your html element on your website.
<html lang="en" class="scroll-smooth"></html>
Add an element with an id to your website:
<div id="top"></div>
Then add a link to that id:
<a href="#top">Scroll to Top</a>
That's it! You can now smooth scroll to any element with an id on your page.