✅ How Scrollspy Works
Scrollspy watches a scrollable container (like <body> or a <div>) and updates classes on nav items (.nav-link) based on which target section is in view.
Basic Scrollspy Setup (Bootstrap 5)
✅ 1. Include Bootstrap CSS & JS
✅ 2. HTML Structure
Key Attributes
| Attribute | Purpose |
|---|---|
data-bs-spy="scroll" |
Activates Scrollspy on the container |
data-bs-target="#..." |
Selector for the nav element to update |
data-bs-smooth-scroll |
Optional: enables smooth scrolling |
tabindex="0" |
Needed if target is body to make it focusable |
⚠️ Notes
-
The target nav element must contain anchor tags (
<a href="#section">) that matchidattributes of content. -
Scrollspy requires scrollable containers—usually
<body>or a custom<div>. -
The container must be large enough to scroll (set
heightandoverflow-y: autofor custom containers).
