To enable smooth scrolling when clicking an <a>
tag in any website, you can add the below CSS code. If you want all anchor links to scroll smoothly, you can do so by applying the scroll-behavior
property in your global CSS.
Steps:
- Create/Modify your global CSS file (e.g.,
styles/globals.css
):
html {
scroll-behavior: smooth;
}
This will ensure smooth scrolling across the entire page whenever the user clicks on an anchor link that targets a section of the page.
- Ensure your links use proper anchor navigation in your components:
<a href="#section-id">Scroll to Section</a>
<div id="section-id">
<h2>Target Section</h2>
<!-- Your content here -->
</div>
By adding scroll-behavior: smooth;
to the html
element, all anchor navigation (<a href="#id">
) will scroll smoothly. This solution works not only in a standard html page but also in React/Nextjs websites.