πŸŒ€ CSS scroll-behavior β€” Complete Tutorial

The CSS scroll-behavior property controls how scrolling happens when a user clicks anchor links, uses keyboard navigation, or triggers scrolling through JavaScript. It lets you enable smooth, animated scrolling without JavaScript.

>>β€œOne line of CSS is enough to make your entire website scroll smoothly.”

Note

βœ” Works on elements with scrollable overflow

βœ” Works on the document (via html) and individual scroll containers

βœ” Doesn’t affect mouse wheel scrollingβ€”only programmatic or anchor scrolling

πŸ“¦ Syntax

scroll-behavior syntax

scroll-behavior: auto | smooth;
ValueDescription
autoInstant jump (default behavior)
smoothSmooth animated scrolling

✨ 1. Enable Smooth Scrolling Website-Wide

Apply to html to affect the whole page.

Global smooth scroll

html {
  scroll-behavior: smooth;
}

Note

Great for single-page websites with anchor navigation.

✨ 2. Smooth Scrolling Inside a Container

Works on any element that has scrolling.

Container scroll behavior

.scroll-box {
  overflow-y: auto;
  scroll-behavior: smooth;
}

✨ 3. Smooth Scrolling + Anchor Links

When a user clicks a link like<a href="#section3">Go to Section 3</a>the scroll animation becomes smooth.

Anchor example

html {
  scroll-behavior: smooth;
}

✨ 4. Works With JavaScript Scrolling Too

JS scrolling with smooth behavior

document.querySelector('#box').scrollIntoView();  // scrolls smoothly

Note

If scroll-behavior: smooth is set on a scrollable element, JavaScript scrolling automatically becomes smooth too.

πŸ“Œ 5. Per-Element Smooth Scroll

This allows your UI components to have different scroll behaviors.

Different elements, different scroll-behavior

.modal {
  scroll-behavior: smooth;
}

.sidebar {
  scroll-behavior: auto;
}

πŸ“Œ 6. Scroll Snap + Scroll Behavior

Combining scroll snapping with smooth scrolling results in a clean slider/carousel feel.

Smooth scroll + snap

.carousel {
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;
}

πŸ§ͺ Real-World Use Cases

1️⃣ Single-Page Navigation

Navbar anchors

html { scroll-behavior: smooth; }

2️⃣ Chat Apps

Chat autoscroll

messages.scrollTo({ top: messages.scrollHeight })

3️⃣ Animated Carousels

Horizontal smooth scroll

.slider { scroll-behavior: smooth; }

⚠️ Common Mistakes

  • ❌ Expecting it to animate mouse-wheel or touch scrolling (it doesn’t)
  • ❌ Applying it to non-scrollable elements
  • ❌ Forgetting scroll container must have overflow enabled
  • ❌ Assuming scroll-behavior works in iframes (often restricted)

πŸ”₯ Summary

The scroll-behavior property enables smooth, native scrolling with zero JavaScript. It's perfect for modern navigation, sliders, modals, and scrollable UIs.

>>β€œOne tiny CSS property β€” a massive upgrade to your UX.”