Native smooth scroll
In a previous post about smooth scrolling I used javascript to scroll smoothly. But...
There is a native way to do this with just css and hashbang url. Bang bing boom!
html {
font-size: 62.5%;
overflow-x: hidden;
scroll-behavior: smooth;
}
/*and use prefer reduced motion media query to disable it for users that prefer reduced motion.*/
@media screen and (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
This makes anchor links scroll smoothly, just target an unique id with a hashbang url.
Get to know me better <a href="#main">here</a>
Further down the page:
<main id="main">
<h1>Scroll?</h1>
</main>
Also use the scroll-margin-top
property for offsetting the scroll position.
#main {
scroll-margin-top: 5rem;
}
See it in action on this page. Click the link below to scroll to the main content.
See the Pen Native smooth scroll by Wonky (@Wonky) on CodePen.
Alright, thanks! Btw, this is my first post this year, woohoo! 🎉
- Next: Container queries are coming
- Previous: My new home on wheels