Davor Suljic created a fork of my Smooth Scrolling Sticky ScrollSpy Navigation that — instead of using
IntersectionObserver — uses some background magic to highlight the active navigation items. The result is a “Pure CSS” implementation:
If you turn on an outline on one of the content sections it becomes clear how it exactly works:
- The content sections also appear underneath the navigation
- The content sections have background set, which has the exact same dimensions as their linked navigation item.
- The backgrounds are positioned visually underneath their linked navigation item using
It’s a delicate combination, but I’m pretty excited that this actually works 🙂
Do note though:
- You’ll need to add an extra wrapper whose width is limited around the section’s content, to prevent the content from appearing underneath the navigation.
Active state is a bit tricky:
- Items high up the navigation list — such as Authentication — will become active pretty late, whereas items lower in the navigation bar — such as Expanders — will get their active state applied quite early. This is because the active state of nav items “starts” when the top of its linked container intersects with the nav item itself.
- For small content-sections — such as Links – the nav item will become inactive too early, even before its linked section has left the viewport (and even when it still entirely in view). This is because the content itself is not that big and the nav item is pretty low in the navigation list.
- You’re limited to background effects only. No making the nav items bold/italic, or changing their color.