By default, the auto-scroll (triggered, for example, by clicking on anchor links) simply “jumps” to the target element (instant scrolling).
Instead, smooth scrolling will create a nice scrolling animation that simulates real user scrolling.
Scroll-behavior
We can create this smooth scrolling effect using the native scroll-behavior
CSS property:
html {
scroll-behavior: smooth;
}
This smooth scrolling can be applied to the entire page by adding this CSS property to a global element (for example, html
), as in the example above.
Alternatively, it can be applied to a particular section (container) to create this effect within a specific area.
This CSS property is well supported by the vast majority of browsers.
Accessibility adjustments
It is always important to consider user preferences.
If the user has requested to minimize motion animations by adjusting the accessibility settings on their system, smooth scrolling should be disabled.
This can be done using something like the following SCSS code:
html {
// Enable smooth scrolling on the entire page.
scroll-behavior: smooth;
// Disable smooth scrolling if the user has requested to minimize motion-based animations.
@media (prefers-reduced-motion: reduce) {
scroll-behavior: auto;
}
}