DEV Community

EinLinuus
EinLinuus

Posted on

Fixed navigations and sections - here is scroll-padding

When having a fixed navigation bar at the top, you might came up with the same problem:

You create a link to scroll to another section on the page, but the fixed navigation bar at the top hides the headline of the section the browser scrolled to.

scroll-padding-top: 100px;

image

That's it. This CSS property adds 100px space between the element with the ID you want to scroll to and the page top. The only thing you have to do now is to replace the 100px with the height of your navigation bar and maybe a bit of extra space.



html {
   scroll-padding-top: 100px;
}


Enter fullscreen mode Exit fullscreen mode

Live example

That's not all

You can also use scroll-padding, scroll-padding-bottom, scroll-padding-right and scroll-padding-left.

Compatibility

image Source: caniuse.com

Top comments (3)

Collapse
 
oyegokepraise profile image
Emerald RLM

It conflicts with Javascript scroll to top

window.scrollTo(0,0 )

I had been making a trade-off between a scroll to top button and scroll padding, please respond if there is a way to resolve this conflict

Collapse
 
einlinuus profile image
EinLinuus

My idea would be to calculate the height of your header/navigation (with JS) and scroll to that position. If your header is 100px height, then scroll to 100px on the Y axis instead of 0. That's the only idea I have currently :/

Collapse
 
callumflack profile image
Callum Flack

You can set the scroll-behaviour to smooth on the html element, and keep it CSS only, don't need JS anymore: developer.mozilla.org/en-US/docs/W...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.