Smoothly scroll to elements on the document with zero dependencies. Yup, that’s right. Lovely smooth scrolling, with no need to load JS libraries.
How to use native smooth scrolling in Javascript
With just a couple of lines of code, you can smoothly scroll users to elements with Javascript.
el.scrollIntoView({ behavior: 'smooth' })
How to use native smooth scrolling in pure CSS
Depending on your use case, it might be possible to smoothly scroll a user to an element with pure CSS. For example, from a back to top link like to.
<style> html { scroll-behavior: smooth; } </style> <a href="#top" title="Back to top">Back to top</a>
See this Codepen for an example.
Potential issues
There has been a few who have mentioned on social media about how scroll-behavior: smooth;
feels buggy when using internal page search in the browser. Chris Coyier mentioned this on Twitter with Christian Schaefer suggesting that perhaps html:focus-within
would be a better solution than applying directly to html
. The only other caveat, according to Christian Schaefer, is that in order for this to work, you also need to add tabindex="-1"
to elements you wish to be scrolled to smoothly.
See this Codepen for an example.
Browser support for native smooth scrolling
Support is actually pretty good, but (at the time of writing) there are a few issues on Safari, without it supporting the smooth behavior options.
Support for scrollIntoView
Support for scroll-behavior