TIL about CSS scroll-margin
I am working on the bigbrowser documentation website, and the page has a sticky navigation bar at the top.
Everything was working well until I decided to add a basic table of content. Clicking on a section would scroll to the correct location, but the section title was hidden behind the sticky navbar.
It turns out there’s a CSS property designed to help with this use case: scroll-margin-top.
It’s mainly used for “scroll snapping” (which I’d never heard of before either). This helps implement carousel-style scrolling where content “snaps” into place (the MDN page shows an example). But since it also affects anchored links scroll positions, that’s exactly what I needed.
Here’s the fix, it can be applied to headings directly, and anchored links will magically have a 80px margin top:
#docs h2[id],
#docs h3[id] {
scroll-margin-top: 80px;
}
I had no idea that “offsetting” the scroll was natively supported in CSS, it’s quite nice not having to resort to any hack!
