When you click an anchor link, the browser scrolls the target element to the very top of the viewport. If your site has a sticky header, the header will overlap the content. scroll-margin-top fixes this with a single line of CSS.
{
scroll-margin-top: 4rem;
}Apply this to any element that is used as an anchor target. The browser will leave 4rem of space above the element when scrolling to it.
If your sticky header is 80px tall, set the offset slightly above that:
/* Apply to all anchor targets */
section[id], div[id], h2[id], h3[id] {
scroll-margin-top: 5rem;
}
/* Or target a specific section */
#about {
scroll-margin-top: 100px;
}If you are not using a table of contents plugin, add this CSS globally to your site to cover all anchor targets at once:
[id] {
scroll-margin-top: 4rem;
}rem units so the offset scales with your root font size.scroll-behavior: smooth to html for a polished effect.