Scroll to top CSS

Scroll to top CSS
CSS and JavaScript solutions to scroll to the top of page

Below is the effect, and you can notice it jumps to the page-top straight away without any smooth effect.

Scroll to top CSS
Basic CSS solution for jump to the top of page

2. CSS Solution with Smooth Scrolling

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

Here is the result with a smooth scrolling effect.

Scroll to top CSS
CSS solution with scroll-behavior for jump to the top of page

However, make sure that you are aware of not all browser supports scroll-behavior

Scroll to top CSS
scroll-behavior browser support

JavaScript Solution

You might need to trigger scrolling with JavaScript, in which case here are some options:

  1. window.scrollTo()
  2. document.documentElement.scrollTop()
  3. window.scroll()
  4. document.documentElement.scrollIntoView()

1. window.scrollTo()

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.

For example without CSS smooth effect:

The result is:

Scroll to top CSS

For example with CSS scroll-behavior:

will give you the smooth scrolling effect, but be aware of the browser support issue for scroll-behavior (as shown previously).

Scroll to top CSS
window.scrollTo with css smooth scrolling

2. window.scroll

If you are not using CSS for the smooth scrolling effect, you can force the smoothness in JavaScript window.scroll()

For example

Shall also give you the smooth scrolling effect:

Scroll to top CSS
window.scroll with smooth scrolling

But be aware of the browser support for ScrollToOptions

Scroll to top CSS
source from https://caniuse.com/#search=ScrollToOptions

3. document.documentElement.scrollTop

The Element.scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. document.documentElement.scrollTop is scrollTop being used on the root element (the element).

And here is the result, and clearly there isn’t any smooth effect. But this property is supported by almost all browsers.

Scroll to top CSS
scrollTop property to scroll to the page top

4. document.documentElement.scrollIntoView()

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user. document.documentElement.scrollIntoView() is a special case which scrollIntoView being used on the root element (the element).

Some browser support scrollIntoViewOptions which allows transition animation.

Scroll to top CSS
scrollIntoViewOptions browser support https://caniuse.com/#search=scrollIntoViewOptions

For example:

Will also give you the smooth scrolling effect:

Scroll to top CSS
scrolling effect with scrollIntoView

Enjoy!

And that’s about it. Thanks for reading.