Simple CSS trick to create a smooth scrolling effect

We use different jquery library or write plain vanilla javascript to achieve a smooth scrolling effect.
jQuery Syntax:
//Smooth scrolling with links
$('a\[href*=\\\\#\]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
$('html,body').animate({scrollTop:$(location.hash).offset().top}, 500);
});
I love CSS. And I wonder can we achieve this effect by using just CSS properties. Then I encounter this native CSS feature scroll-behavior
.
The scroll-behavior
property in CSS allows us to define whether the scroll location of the browser jumps to a new location or smoothly animates the transition when a user clicks a link that targets an anchored position within a scrolling box.
If you click a #hash link, the native behaviour is for the browser to change focus to the element matching that ID. The page may scroll, but the scrolling is a side effect of the focus changing.
Example
html {
scroll-behavior: smooth;
}
It also has a different syntax,
/* Keyword values */
scroll-behavior: auto;
scroll-behavior: smooth;
/* Global values */
scroll-behavior: inherit;
scroll-behavior: initial;
scroll-behavior: unset;
Just take a look a sample HTML
<nav>
<a href="#page-1">1</a>
<a href="#page-2">2</a>
<a href="#page-3">3</a>
</nav>
<div class="scroll-container">
<div class="scroll-page" id="page-1">1</div>
<div class="scroll-page" id="page-2">2</div>
<div class="scroll-page" id="page-3">3</div>
</div>
CSS
html {
scroll-behavior: smooth;
}
Browser compatibility
Conclusion
👏👏 By coming this far I hope you can use this awesome CSS smooth scrolling effect. So, I suggest you give it a try on your project and enjoy it!
Feel free to share your thoughts and opinions and leave me a comment if you have any problems or questions.
Till then,
Keep on Hacking, Cheers