CSS scroll offset fix for sticky menus

If you have a site with a sticky navbar menu you may have found that anchor jump links targetting a section of the page are obscured by the sticky navbar.

There is an easy CSS solution for creating an offset to solved this:

[id]:target {
    padding-top: 130px !important;
    margin-top: -130px !important;
}

What this does is target all IDs on the page and if the ID matches the value of the URL hash, it will create an invisible offset. For my purposes, the sticky nav was 90px tall, so I upped this to 130px to allow a little room. You can adjust this to suit your needs.

Soon, this additional CSS solution below should work, however it does not yet work in Safari on macOS & iOS.

html {
    scroll-behavior: smooth;
}
[id] {
    scroll-margin-top: 130px;
    scroll-snap-margin-top: 130px;
}

/* disable when user has indicated they prefer reduced montion */
@media screen and (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}

Leave a comment