
Prevent content from being hidden underneath a fixed header by using scroll-margin-top
Prevent content from being hidden underneath a fixed header by using scroll-margin-top êŽë š

If youâve ever implemented a design with a fixed header, youâve surely had this problem:
You click a jump link like
<a href="#header-3">Jump</a>which links to something like<h3 id="header-3">Header</h3>. That's totally fine, until you have aposition: fixed;header at the top of the page obscuring theh3you're trying to link to!Fixed headers have a nasty habit of hiding the element youâre trying to link to.
Thankfully Chris Coyier from CSS-Tricks found and shared the straightforward solution:
h3 {
scroll-margin-top: 5rem; /* whatever is a nice number that gets you past the header */
}
Update đ
As noted in the comments below this doesnât work Safari. In that browser youâll need to use scroll-snap-margin-top. All other modern browsers do have excellent support for scroll-margin-top and play nice.
To not have to apply the CSS rule to too many elements, Iâd adjust the snippet to use the :target selector.
The
:targetCSS pseudo-class represents a unique element (the target element) with anidmatching the URLâs fragment.
That way it will work with any internally linked thing (headers in all their sizes, anchors, etc):
:target {
scroll-margin-top: 5rem;
}
It was also nice to see that Mattias Geniar used this solution when implementing the Smooth Scrolling Sticky Navigation I wrote about earlier (Mattias is using scroll-padding-top though).
Fixed Headers and Jump Links? The solution is scroll-margin-topâ