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.

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.

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-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:

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].

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:

window.scroll with smooth scrolling

But be aware of the browser support for ScrollToOptions

source from //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.

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.

scrollIntoViewOptions browser support //caniuse.com/#search=scrollIntoViewOptions

For example:

Will also give you the smooth scrolling effect:

scrolling effect with scrollIntoView

Enjoy!

And that’s about it. Thanks for reading.

Video liên quan

Chủ Đề