Smooth Scroll CSS
CSS 2 CommentsIn this Smooth Scroll CSS tutorial, I will show you how to do a smooth scrolling using pure CSS with an easy and single line of code, also drive you in detail of the document.
As a web developer, I also used to do smooth scrolling on many websites as it looks so good when you scroll. But a year ago I used to do it with a very long code of JavaScript as below:
// Select all links with hashes $('a[href*="#"]') // Remove links that don't actually link to anything .not('[href="#"]') .not('[href="#0"]') .click(function(event) { // On-page links if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) { // Figure out element to scroll to var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); // Does a scroll target exist? if (target.length) { // Only prevent default if animation is actually gonna happen event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000, function() { // Callback after animation // Must change focus! var $target = $(target); $target.focus(); if ($target.is(":focus")) { // Checking if the target was focused return false; } else { $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable $target.focus(); // Set focus again }; }); } } });
I always felt weird to include this much code just for Smooth Scroll CSS But, now there is an easy and shortest way to do that. So I decided to wrote an article about it. Here is you can do that using pure CSS.
The scroll-behavior
property in CSS specifies how the user goes to the specific location in the current page smoothly OR straight jump. The scroll-behavior
property mainly accepts two values those basically switch the scroll behavior between smoothly OR straight jump.
Example
.module { scroll-behavior: smooth; }
Syntax
scroll-behavior: auto; scroll-behavior: smooth;
Values
auto
:- The scrolling box scrolls instantly.
smooth
:- This value makes the scroll smooth with a user-agent-defined timing.
Note that any other scrolls, such as those 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. This property specified on the
source MDNbody
element will not propagate to the viewport. and User agents are allowed to ignore this property.
Live Preview
Browser Support
Browser support is around 75%, and coming to Edge 76 soon.
Property | |||||
---|---|---|---|---|---|
scroll-behavior | 61.0 | Not supported | 36.0 | Not supported | 48.0 |
More Info at csswg, Microsoft Edge Platform, Chrome Platform Status
That’s all, Thanks for reading. 🙂 Share with love.
William
Thanks for sharing, Really helpful!!
Rajnish Rajput
Thank you William, your feedback really appreciated.