Loading...

How to scroll smoothly to any section of the page with just one line of css?

question css front-end
Ram Patra Published on September 22, 2024

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:

  1. 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.

  1. 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.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on September 22, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question front-end css January 3, 2024 What's the difference between SCSS and Sass?

Sass (Syntactically Awesome Style Sheets) and SCSS (Sassy CSS) are both preprocessors that extend the capabilities of standard CSS, allowing for variables, nested rules, mixins, and more. However, there’s a common misunderstanding about the differences between Sass and SCSS. They are not actually two different languages; rather, they are two different syntaxes for the same Sass preprocessor.