We're used to sticky headers that move along with our scroll in the website. For some websites (like Amazon) it offers users a way to access the most important pages of the website. Or for some websites like news sites and blog, it offers a way for users to get back to the home page or search for new article, after reading a lengthy article.
One big issue or problem we may face while implementing sticky headers are anchor links. Generally, when you click an anchor link on a page, the section would snap to the top of the document. But with a sticky header in place, some content in the anchor section would go behind the sticky header.
On a side note, if you want to achieve smooth scrolling instead of the snap when clicking on an anchor link, then read our article on it.
Now usually we do some dirty tricks to avoid those issue. Like adding extra padding and margin to the top of the anchor section/DIV so that the sticky header won't cover it. But this would mostly add lots of unwanted space around the website.
Time to avoid those, as we have a one-liner CSS code to fix this issue.
scroll-margin-top CSS property
In CSS there is the scroll-margin-top property which is intended exactly for this type of situation. The CSS property lets you define a top margin for an anchor section, that the browser would use when snapping a scrolled element into place. You could learn more about this property in MDN web docs.
scroll-margin-top: <value>;
Here you could add any value in px, em or rem and the browser would leave a margin of that value at the top when snapping to the anchor section.
For example, you could add the scroll-margin-top CSS property to an anchor section, with a value of 2em. Now when you click the anchor link, the browser jumps to the anchor section and will leave a margin of 2em at the top. Thus, the sticky header won't hide any content of that section.
You may need to adjust the scroll-margin-top value based on the height of your sticky header.
<div class="section" id="anchorone">
<h3>Section One</h3>
<p>Some some some content here</p>
</div>
.section {
color:#ffffff;
background: #00000;
height:50vh;
margin:0;
scroll-margin-top : 2em;
}
Here is a working example of the same -
The best thing about this CSS property is that it applies only to scroll snapping. It won't add any actual margin to the anchor section. Thus the section would still have its user-defined margin within the context of the document.
Note: scroll-margin-top CSS property supports the majority of modern web and mobile browsers including Chrome 69+, Firefox 68+, Opera 56+ and Edge 79+. As always IE won't support it.