Scroll Padding Top with a custom CSS property

Set a custom CSS property as the ‘scroll-padding-top’ value.

Use JavaScript to get the height of the (position: fixed;) header. Then set the value of the custom CSS property to be the header’s height value.

The fallback (in case JS is disabled) is 200px and should be adjusted as needed to some approximate size of the header.

We also add 32px to the headerHeight value so that there is some breathing room but this can be adjusted as well.


const scrollPaddingTop = () => {
    const headerHeight = header.offsetHeight'--scroll-padding', headerHeight + 32 + 'px')


html {
   scroll-behavior: smooth;
   scroll-padding-top: var(--scroll-padding, 200px);