This post was inspired by "Stop Using Fixed Headers and Start Using Sticky Ones" by Luis Augusto, where he explained why position: fixed
is an inferior way of sticking headers.
Stop Using Fixed Headers and Start Using Sticky Ones
Luis Augusto ・ Jun 25 '20 ・ 2 min read
Problem
I want to add one tip for anyone doing sticky/fixed headers while keeping internal links working correctly. If you have a long page, you might include a table of contents that links to sections on the page.
See this example from our documentation site:
By default, when you click on an internal link, the browser scrolls the page just below that element, which will cause it to be invisible for the user. This causes confusion. It is even worse if you have a fixed/sticky header on your website like we do because even more content will be covered due to this behavior.
See an example from our documentation site after clicking on "Output":
This behavior is not user-friendly, so in the old days there were multiple hacks to fix it - I usually resorted to JavaScript because it didn't leave a trace in CSS or HTML.
The modern solution
In 2020, there is a better way: use the CSS property called scroll-margin-top
. Add it to a header that you are linking to, and the browser will subtract this value when scrolling. In our case we added:
main h2, main h3 {
scroll-margin-top: 95px;
}
And now, after clicking on "Output":
We get a much better experience with a native-only solution.
Read more on scroll-margin on CSS-Tricks.
Read more
If you are interested in more performance oriented content, follow me and I promise to deliver original, or at least effective methods of improving your website.
Top comments (0)