CSS Scroll Padding
This weekend I ran across I hot tip by Jeffrey Yasskin which highlighted a CSS property I hadn't encountered before, scroll-padding-top
:
Best kept secret for websites with fixed headers: scroll-padding-top (https://t.co/L7muNZV9d5) can make fragment links scroll the fragment to somewhere visible instead of under the header.
— Jeffrey Yasskin (@jyasskin) April 16, 2020
I promptly added this new property to a project I'm currently working on, and now I've got some nice scroll functionality, no JavaScript required.
In my case the height of my app's sticky header is different between the mobile and desktop view, so I took advantage of CSS custom properties:
html {
--navbar-height: 57px;
scroll-padding-top: calc(var(--navbar-height) + 47px);
}
@media (min-width: 768px) {
html {
--navbar-height: 73px;
}
}