Smooth scrolling is a popular scrolling behavior in most of the one page websites like landing pages. In this article I am gonna show you 4 different ways to create this effect. One way using only CSS, while the others using javascript.

4 different ways to make smooth scrolling:

  1. CSS scroll-behavior.
  2. window.scrollTo().
  3. window.scroll().
  4. element.scrollIntoView().

1. CSS scroll-behavior

By adding html {scroll-behavior: smooth;} to the CSS code this will affect the scroll behavior of the whole page.

See the Pen CSS scroll-behavior by Islam Sayed (@islam-codehood) on CodePen.

Browser Support

https://caniuse.com/css-scroll-behavior

2. window.scrollTo()

This is a window built-in method. This means that it is called on the window object. It can take an object as an argument.

Syntax

window.scrollTo({
  top: <element top position on page>,
  behavior: "smooth"
})

where the top property is a number that represents the number of pixels along the Y axis to scroll the window.

See the Pen window.scrollTo() by Islam Sayed (@islam-codehood) on CodePen.

Browser Support

https://caniuse.com/element-scroll-methods

3. window.scroll()

It is the same like scrollTo() method.

See the Pen window.scroll() by Islam Sayed (@islam-codehood) on CodePen.

Browser Support

https://caniuse.com/element-scroll-methods

4. element.scrollIntoView()

This one is a method of the Element object. This means that it should be called on the element itself.

Syntax

element.scrollIntoView({
    behavior: "smooth",
    block: "center"
})

where the block property is the vertical alignment of the element. It can be either start, center, end, or nearest. Default value is start.

See the Pen elem.scrollIntoView() by Islam Sayed (@islam-codehood) on CodePen.

Browser Support

https://caniuse.com/scrollintoview