Need to scroll to the top of the page?

Avatar of Chris Coyier
Chris Coyier on

Perhaps the easiest way to offer that to the user is a link that targets an ID on the <html> element. So like…

<html id="top">
     <!-- the entire document -->
     <a href="#top">Jump to top of page</a>

But we’ve got a few options here.

If you want it to smooth scroll up to the top, you can do that in CSS if you like:

html {
  scroll-behavior: smooth;

Note that placing a property on the HTML element like that is all-encompassing behavior you don’t have much control over.

In this case, we aren’t linking to a focusable element either, which means that focus won’t change. That’s probably important, so this would be better:

     <a id="top"></a>
     <!-- the entire document -->
     <a href="#top">Jump to top of page</a>

It’s better because the focus will move to that anchor tag, which is good for people using the keyboard or assistive technology.

These require clicks though. You might need to trigger scrolling within JavaScript, in which case:

window.scrollTo(0, 0);

…is a sure bet to scroll the window (or any other element) back to the top. The scrolling behavior of that is determined by CSS as well, but if you aren’t doing that, you can force the smoothness in JavaScript:

  top: 0, 
  left: 0, 
  behavior: 'smooth'

For a more complete story about smooth scrolling, we have a page for that.