0
0
CssConceptBeginner · 3 min read

CSS scroll-behavior: Smooth Scrolling Explained

scroll-behavior is a CSS property that controls how scrolling happens when a user clicks a link or uses JavaScript to scroll. It lets you choose between instant jumps or smooth scrolling animations.
⚙️

How It Works

Imagine you have a long webpage and you want to jump to a section far down. Normally, the page jumps instantly, like flipping a page in a book quickly. With scroll-behavior, you can make the page scroll smoothly, like sliding down a gentle ramp.

This property tells the browser how to handle scrolling triggered by anchor links or JavaScript. You set it on a container (often html or body), and when the user clicks a link or code scrolls the page, the browser follows the chosen behavior.

💻

Example

This example shows how to enable smooth scrolling on the whole page. Clicking the link scrolls down smoothly instead of jumping instantly.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scroll Behavior Example</title>
  <style>
    html {
      scroll-behavior: smooth;
    }
    section {
      height: 100vh;
      padding: 2rem;
      border-bottom: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <nav>
    <a href="#section2">Go to Section 2</a>
  </nav>
  <section id="section1">
    <h1>Section 1</h1>
    <p>Scroll down to see smooth scrolling in action.</p>
  </section>
  <section id="section2">
    <h1>Section 2</h1>
    <p>You arrived here smoothly!</p>
  </section>
</body>
</html>
Output
A webpage with two full-screen sections and a link at the top. Clicking the link smoothly scrolls the page from Section 1 to Section 2.
🎯

When to Use

Use scroll-behavior when you want to improve user experience by making page navigation feel natural and smooth. It is great for single-page websites, long articles, or any page with anchor links.

It also helps when you use JavaScript to scroll to parts of the page, making the movement less jarring. Avoid it if you want instant jumps for speed or accessibility reasons, but most users prefer smooth scrolling.

Key Points

  • scroll-behavior accepts values like auto (default instant jump) and smooth (animated scroll).
  • It only affects scrolling triggered by links or scripts, not manual scrolling by the user.
  • Works in modern browsers and improves navigation feel.
  • Set it on html or body for whole-page effect.

Key Takeaways

scroll-behavior controls how the page scrolls when triggered by links or scripts.
Use scroll-behavior: smooth; to create smooth, animated scrolling.
It improves user experience on long pages or single-page sites with anchor links.
Set it on the html element for best effect.
Not all scrolling (like manual wheel scroll) is affected by this property.