TL;DR
For anchor links like <a href="#section-2">, the browser will jump to the target automatically. To make it smooth, use CSS scroll-behavior. For JS control, prefer Element.scrollIntoView(); if you need exact pixel offsets (e.g., fixed header), compute the position and use window.scrollTo(). Use scroll-margin-top on the target to avoid header overlap, and respect prefers-reduced-motion for accessibility. (MDN Web Docs)
1) CSS-only smooth scrolling for anchors
/* Smooth scrolling for all in-page anchor jumps */ html { scroll-behavior: smooth; }
Works for standard fragment navigation (#id) and for script-triggered scrolling when behavior is auto. See: MDN: scroll-behavior. (MDN Web Docs)
2) Programmatic scrolling to an element (modern)
document.querySelector('#section-2')?.scrollIntoView({ behavior: 'smooth', // or 'auto' block: 'start', // 'start' | 'center' | 'end' | 'nearest' inline: 'nearest' });
Element.scrollIntoView() supports options for vertical/horizontal alignment and smooth behavior. Docs: MDN: Element.scrollIntoView(). (MDN Web Docs)
Fixed header tip: if a sticky/fixed header hides the top of your section, add an offset on the target:
#section-2 { scroll-margin-top: 72px; } /* header height */
Docs: MDN: scroll-margin-top. Browser notes: Can I use. (MDN Web Docs)
3) Pixel-precise scrolling (compute + scrollTo)
const el = document.querySelector('#section-2'); const y = el.getBoundingClientRect().top + window.pageYOffset - 72; // header offset window.scrollTo({ top: y, behavior: 'smooth' // 'auto' for instant });
Docs: MDN: window.scrollTo(). (window.scroll() is effectively the same.) (MDN Web Docs)
4) Accessibility: honor “reduced motion”
@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } /* disable smooth scrolling */ }
Docs: MDN: prefers-reduced-motion. Support: Can I use. (MDN Web Docs)
Summary
Use CSS scroll-behavior: smooth for anchor links. (MDN Web Docs)
Prefer el.scrollIntoView({...}) for programmatic scrolling. (MDN Web Docs)
For fixed headers, set scroll-margin-top on targets. (MDN Web Docs)
When you need exact offsets, compute and call window.scrollTo({ top, behavior }). (MDN Web Docs)
Respect prefers-reduced-motion. (MDN Web Docs)