How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript

Give your users a seamless experience by testing on 3500+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Guide Banner Image
Home Guide How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript

How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript

Front-end development has evolved from simple pages to feature-rich web applications, influencing how users navigate content. Smooth scrolling enhances user experience by replacing abrupt jumps with fluid transitions, making web navigation more seamless.

Overview

Smooth scrolling is a gradual, animated transition to a target section on a webpage instead of an instant jump.

Key Benefits:

  • Provides a fluid and visually appealing navigation experience.
  • Improves readability and user engagement by reducing sudden jumps.
  • Enhances accessibility, helping users track movement on the page.
  • Works well for single-page websites and long-scrolling pages.

How to Implement:

  • Add a click event listener to navbar links.
  • Use preventDefault() to stop anchor tag auto-scroll.
  • Set the top value to define scroll distance.
  • Store the href value in a variable and apply smooth scrolling.

This article explores smooth scrolling, its benefits, how to implement it using HTML, CSS, and JavaScript, and ensuring browser compatibility for a seamless user experience.

What is Smooth Scrolling

Smooth scrolling is a visual effect where the webpage content glides gradually to a target position (like a section or element) instead of jumping instantly.

It enhances user experience by making navigation feel more natural and polished, especially when clicking anchor links or scrolling programmatically using JavaScript or CSS.

For example, clicking a link to #about smoothly scrolls the page to the “About” section rather than snapping instantly to it.

Why add Smooth Scrolling to your Project?

Due to its great demand and aesthetically appealing user experience, major internet browsers support this feature. Here are some other reasons why it is beneficial:

  • Enhances User Experience: Provides a fluid and natural transition between sections, avoiding abrupt jumps.
  • Improves Accessibility: Makes navigation easier, reducing eye strain and enhancing readability.
  • Ideal for Single-Page Websites: Smoothly scrolls to different sections, improving usability for long-form content.
  • Adds a Polished Look: Creates a modern, visually appealing browsing experience.
  • Easy to Implement: Can be integrated seamlessly using built-in browser features or third-party libraries.

Creating Web Page for Smooth Scrolling Example

To begin with, create a simple web page and set up the HTML and CSS for it to demonstrate Smooth Scrolling. The sample web page looks like the image below.

Webpage for Smooth Scrolling using CSS and JavaScript

Setting up the HTML for Smooth Scrolling

Use the code below to set up the HTML of the web page.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">

    <title>Smooth Scroll</title>

</head>

<body>

    <header>

        <nav>

            <a href="#home">Home</a>

            <a href="#section1">Section 1</a>

            <a href="#section2">Section 2</a>

        </nav>

    </header>




<section id="home">HOME</section>

<section id="section1">SECTION 1</section>

<section id="section2">SECTION 2</section>




//Script Section for Vanilla Js and jQuery

<script src="script.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</body>

</html>

Setting up the CSS for Smooth Scrolling

Use the below code to set up CSS and ensure that the sections have enough spacing.

section{

    min-height: 100vh;

    display: flex;

    align-items: center;

    justify-content: center;

    font-size: 7em;

    color: grey;

    font-weight: bolder;

    font-family: 'Franklin Gothic Medium', 'Arial Narrow';

} 

How to make smooth scroll in CSS

With the help of CSS, you can achieve smooth scrolling in just one line of code. This is possible because of a standard property available in the CSS, which is known as the scroll-behavior property.

This property could be added to the entire document, which will enable smooth scrolling to all the required elements or you could add it to a specific element or a scroll container.

Just add scroll-behavior: smooth to the <html> element in your CSS file.

html{

    scroll-behavior: smooth;

}

However, the scroll-behavior accepts four values.

The four values are ‘Auto’, ‘Smooth’, ‘Initial’, ‘Inherit’. All these four values are responsible for four different behaviors of scrolling.

autoThis follows the default trend of the scroll behavior, it will create a jump effect.
smoothThis is the value needed to enable smooth scrolling with the help of CSS.
initialThis sets the property to its default value in CSS. In this case, initial and auto work the same.
inheritThis will take the property from its parent element.

Browser-compatibility of CSS Scroll Behavior

Although CSS solves the problem with just one line of code. Still, it is not the preferred way to achieve smooth scrolling on the webpage. It is because this CSS property is not compatible with a wide range of browsers.

Here are the browsers supporting CSS scroll-behavior.

Browser Compatibility of CSS Scroll BehaviorSource: caniuse

While most of the new browser versions support CSS scroll-behavior fully, some of the browsers like IE, Opera Mini, and KaiOS do not support this at all. Older browser versions also do not support smooth scrolling.

Due to limited browser compatibility, it is essential to perform cross browser testing to check if the smooth scrolling behavior is consistent across browsers and devices. Using real device cloud like BrowserStack Live, you can test your website across 3500+ device browser combinations under real user conditions to deliver a seamless experience.

Talk to an Expert

Apart from this, you do not have much control over the scroll behavior of your webpage. To resolve this, it is recommended to achieve smooth scrolling with the help of JavaScript.

Advantages of JavaScript smooth scroll effect

To understand how to create a smooth scroll effect by JavaScript, let’s first understand what the advantages of JavaScript smooth scroll are:

  1. Browser Support: There are many browsers or browser-versions that do not support the scroll-behavior property mentioned in the smooth scroll CSS transition, JavaScript or JavaScript library is the solution that will work on all the browsers.
  2. Better control: Apart from this, you get more control over the scrolling effect, such as scroll speed, amount of delay, duration of the animation, etc.

How to achieve JavaScript smooth scroll effect?

Now that it is clear why JavaScript is the better option to apply the Smooth Scroll transition effect the following section covers how it is applied with the help of Vanilla JavaScript and with a JavaScript Library such as jQuery.

Using Vanilla JavaScript

Vanilla JavaScript allows for a smooth scrolling transition effect in webpage elements. This can be implemented using the following approach:

  1. Add a click event listener to href in the navbar.
  2. Prevent auto-scroll that occurs due to anchor tag with the preventDefault() function.
  3. To set how much to scroll, determine the top: property.
  4. Save the value of the href element in a variable and apply the method to it with smooth behavior.

Method Using window.scrollTo()/window.scrollTo()/window.scrollBy()

In similarity with the CSS property, in JavaScript, you have to determine the behavior property which will receive the value as smooth.

Follow the code given below

let section = document.querySelectorAll("section");
let navlinks = document.querySelectorAll("header nav a");


for (const link of navlinks) {

  link.addEventListener("click", smoothScroll);

}


function smoothScroll(event) {

  event.preventDefault();

  const href = this.getAttribute("href");


  document.querySelector(href).scrollIntoView({

    behavior: "smooth"

  });

}

jQuery

jQuery is a JavaScript library that is supported in most browsers. If you use jQuery for applying the smooth scroll feature, you get more control than Vanilla JavaScript. Moreover, you get the work done with fewer lines of simple code.

Using the animate() method that is available in the jQuery package, which also allows controlling the time and value of the Scroll directly.

Here is how to implement jQuery

First, let’s import jquery in your project with the help of CDN,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

You can also download jQuery into your project.

Once jQuery is set up, use a similar approach to that used with vanilla JavaScript.

Here is the required jQuery code.

    $("header nav a").on("click", function (e) {

    e.preventDefault();

    const href = $(this).attr("href");

    $("html, body").animate({ scrollTop: $(href).offset().top }, 1000);

});

BrowserStack Live Banner

Using requestAnimationFrame for Custom Smooth Scrolling

Using requestAnimationFrame for Custom Smooth Scrolling allows you to create a finely controlled scroll animation by updating the scroll position frame by frame.

Here’s a basic example of how it works:

javascript

function smoothScrollTo(targetY, duration = 500) {

  const startY = window.scrollY;

  const distance = targetY - startY;

  const startTime = performance.now();




  function scroll(currentTime) {

    const elapsed = currentTime - startTime;

    const progress = Math.min(elapsed / duration, 1); // cap at 1

    const ease = 1 - Math.pow(1 - progress, 3); // ease-out cubic

    window.scrollTo(0, startY + distance * ease);




    if (progress < 1) {

      requestAnimationFrame(scroll);

    }

  }




  requestAnimationFrame(scroll);

}




// Usage: scroll to 1000px from top over 600ms

smoothScrollTo(1000, 600);

This gives you more flexibility than scrollIntoView or scrollTo({ behavior: ‘smooth’ }), and works in older browsers without native smooth scroll support.

ScrollIntoView vs window.scrollTo – Which One to Use?

Both scrollIntoView() and window.scrollTo() are JavaScript methods used for scrolling, but they differ in how and where they scroll, as well as in flexibility and control.

Here are the key differences:

Featureelement.scrollIntoView()window.scrollTo()
TargetScrolls directly to a specific DOM elementScrolls to exact x/y pixel coordinates
Ease of UseSimple, requires only the elementRequires calculating element’s position
Syntax Simplicityelement.scrollIntoView({ behavior: “smooth” })window.scrollTo({ top: y, behavior: “smooth” })
Fine ControlLimited (only aligns to element edges)Full control over scroll direction and amount
Alignment Optionsblock and inline options (start, center, etc.)No built-in alignment options
Use CaseBest when scrolling to an element (e.g., section, button)Best for dynamic or calculated scroll positions
Browser SupportBroad support, but behavior may vary slightlyBroad support, especially with modern options

Comparing Popular Smooth Scrolling Libraries

Here’s a quick comparison of popular JavaScript libraries that enhance or customize smooth scrolling:

1. SmoothScroll.js

It is a lightweight JavaScript library that enables smooth scrolling to anchor links using the browser’s native scroll behavior.

  • Lightweight and easy to integrate.
  • Adds smooth scroll behavior to anchor links.
  • Works with modern browsers using native scroll API.
  • Good for simple use cases.

2. Locomotive Scroll

It is a JavaScript library that adds smooth scrolling combined with parallax effects for visually dynamic web pages.

  • Adds smooth scrolling with parallax effects.
  • Great for visually rich, scroll-driven websites.
  • Requires more setup and styling considerations.
  • Can conflict with native scroll behavior or accessibility.

3. GSAP ScrollToPlugin

It is a plugin for the GSAP animation platform that provides precise, animated scrolling to elements or coordinates.

  • Part of the GreenSock Animation Platform (GSAP).
  • Offers precise control over scroll timing, easing, and triggers.
  • Ideal for complex animations tied to scroll.
  • Heavier and best suited for interactive, animated pages.

4. Lenis

It is a modern, GPU-accelerated scroll library that replaces native scrolling with smooth and customizable scroll behavior.

  • Modern and minimal smooth scroll library.
  • Replaces native scroll with GPU-accelerated custom behavior.
  • Supports scroll events and programmatic scroll.
  • Great performance and flexibility.

Tip: Choose based on your needs. Use SmoothScroll.js or Lenis for simple effects, GSAP for animations, and Locomotive Scroll for high-design or parallax-heavy websites.

BrowserStack Automate Banner

Why test Smooth Scrolling on Real Devices?

Testing smooth scrolling on real devices is essential because:

  • Real hardware reveals performance issues like stuttering, lag, or frame drops that emulators or simulators may miss.
  • Touch behavior and scroll inertia vary across devices and browsers, especially on iOS vs Android.
  • Browser rendering engines interpret smooth scroll differently, what’s smooth on Chrome may not be on Safari.
  • High-resolution screens and refresh rates affect scroll fluidity and animation timing.
  • Real-user experience validation ensures that interactions feel natural and responsive across screen sizes and input types.

Talk to an Expert

BrowserStack is a cloud-based testing platform that lets developers and QA teams test websites and mobile apps across a wide range of real devices and browsers. It eliminates the need for physical device labs, enabling cross-browser and cross-device testing at scale.

Here’s how it can help test smooth scrolling on real devices:

  • Access to Real Devices: Test smooth scrolling on actual smartphones, tablets, and desktops to capture real-world performance, including touch behavior and screen responsiveness.
  • Cross-Browser Compatibility: Instantly verify how smooth scrolling behaves in different browsers like Chrome, Safari, Firefox, and Edge without manual setup.
  • Live Debugging: Use built-in developer tools to inspect scroll animations, fix CSS issues, and debug JavaScript in real time on remote devices.
  • Touch & Gesture Testing: Simulate real touch interactions to see how scroll inertia and responsiveness feel on touchscreens.

Automation Support: Use tools like Selenium, Cypress, and Playwright with BrowserStack Automate to run repeatable smooth scroll tests in your CI pipeline.

Conclusion

A smooth scroll provides a better user experience when someone has to navigate the page. Also, it reduces the choppiness of the page that the sudden jump effect creates with its fast motion.

To implement smooth scrolling in your webpage, these three are the best methods to choose from. If you want to have your website to a large number of users, you must have to go with the  JavaScript option to cover a wide range of browsers. However, in that context, jQuery provides more options than Vanilla JavaScript.

Apart from these, there are hundreds of JavaScript libraries and plugins that can also come to be used for achieving the smooth scroll feature in your website.

However, to ensure that the implementation of smooth scrolling is consistent across different devices and browsers, it is important to test cross-browser compatibility on real devices and browsers. With tools like BrowserStack, you can easily test how smooth scrolling functions under real user conditions and get accurate results.

Test on Real Devices for Free

Tags
Automation Testing Website Testing