DEV Community

Cover image for Scrolling to the Top in CSS
Paweł Kowalski for platformOS

Posted on • Updated on

Scrolling to the Top in CSS

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.

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:

Table of contents

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":

Before

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;
}  
Enter fullscreen mode Exit fullscreen mode

And now, after clicking on "Output":

After

We get a much better experience with a native-only solution.

See a live demo.

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.

Discussion (0)