I am experimenting with a unique combination of a Pure CSS in-page anchoring solution using scroll-behavior: smooth
and scroll-margin-top
settings, along with a sticky header for in-page navigation.
By utilizing IntersectionObserver
, I can identify when the sticky element reaches the top of the page and dynamically apply specific styles to create a sticky header effect, which may change the header's height.
When the header is in its sticky position, users can smoothly scroll to different sections by clicking on links in the in-page sticky navigation, with proper offset adjustment.
The challenge lies in the initial state of the page load and clicking an anchor. If you click on an anchor while the header is not yet sticky, you will scroll to the correct section but with an incorrect offset position. Is there a way to resolve this issue without resorting to a JavaScript solution?
To illustrate these issues, I have created a basic Codepen. For instance, if you click on "Section C" upon page load, it will take you to the wrong offset. However, clicking on "Section C" again after that should lead you to the correct position, as well as other sections. When you initially click on an anchor while the header is not sticky, it will likely take you to the wrong section offset.