10. 6. 2023

Scroll-behavior – smooth scroll using CSS, without Javascript

From time to time, we need to fix & nbsp; smooth scroll & nbsp; between sections using so-called & nbsp; anchors . So we simply create a link and put nothing complicated in the href attribute of the & nbsp; # section-id we want to point to. However, the default behavior of browsers may not be nice at all in some cases, instead of smooth scrolling to a given section, the browser jumps and for a better user experience, this can definitely be solved better.

The most common and easiest option is to use smooth scroll, where the browser window moves smoothly to a given section. There are several ways to accomplish this, the most common is the & nbsp; jQuery solution, which might look something like this:

This solution has its advantages and disadvantages. The biggest disadvantage is clearly the dependence on the huge Javascript library jQuery. For example, you can take advantage of the ability to set the speed, the animation curve, and further adjust the smooth shift.

An unspoken CSS solution

In CSS, we can find a useful & nbsp; scroll-behavior property that can be set to & nbsp; smooth . It can achieve our smooth scrolling quite easily, one line in CSS, without the need for any Javascript.

Demonstration in practice

Browser support

Everything looks beautiful and simple. The big disadvantage here may be the absence of speed settings and the smooth shift animation itself, but in most cases it is still not important.

The main problem at the moment is not much support from browsers, currently it’s & nbsp; only 78.08% . For more detailed support, see Data from Can I use: https://caniuse.bitsofco.de/embed/index.html?feat=css-scroll-behavior&periods=future_1,current,past_1,past_2&accessible-colours=false

But we don’t have to despair too much. As usual, for the & nbsp; CSS scroll-behavior property & nbsp; there is & nbsp; JS pollyfil smoothscroll by iamdustan . Its use consists only in linking a small Javascript and calling its initialization. The question then is whether it is not more advantageous for us in the current project to reach for the good old Javascript solution straight away.

Learn more about CSS scroll properties -behavior.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *