Also available in: Français

Recently in a small project, I had to build something quickly, like a prototype, which contains some little things like a sticky menu, a scroll-spy, mixed with a smooth-scrolling behavior. Some features that often ask to spend time on JavaScript coding. Well, not this time.

The CSS Working Group says…

The CSS WG introduced scroll-behavior in its drafts to allow you to handle the behavior of the scroll inside the scrolling box. Yes, obvious I know. This new feature comes with a few values, only 2 actually:  auto and smooth.

The scroll-behavior property specifies the scrolling behavior for a scrolling box, when scrolling happens due to navigation or CSSOM scrolling APIs. Any other scrolls, e.g. those that are performed by the user, are not affected by this property. When this property is specified on the root element, it applies to the viewport instead.

In other words this property applies on all actions which makes the navigation possible inside a scrolling box, unless the user scrolls by theirselves inside the page, manually.

The magic piece of code

Get to the point.
For my little project, I didn’t care about the support, which is pretty good on Chrome and Firefox already,  so my CSS code used to add smooth-scrolling inside my page is really simple and short:

body {
    scroll-behavior: smooth;

And voilaaaa! Solved!

For those who need a demo with editable code, here is a CodePen.



I leave you here with the support of this CSS feature which is really good for progressive enhancement (IMHO).