How to Add a Smooth Scroll in CSS
Vincent Chosen
Posted On: April 16, 2024
121449 Views
23 Min Read
According to Adobe, 59% of people browse a website with an appealing design. Factors like faster page loads, smooth scroll, dynamic content loading, etc., can go a long way in improving the overall time spent on the site. Therefore, user engagement and time spent on your websites are mostly influenced by the quality and relevance of your web design and content.
Smooth scroll in CSS is a critical aspect of web design that contributes to an excellent user experience. Navigating through different web page sections becomes effortless with smooth transitions, which makes it easier for people to explore the content. Adding a smooth scroll in CSS to your website can be implemented using the scroll-behavior property that streamlines the entire process.
In this blog, we will look at the scroll-behavior property, which can be used to add a smooth scroll in CSS. We’ll look at how it can improve the scrolling experience for users with just one line of code.
- Understanding Browser Scroll Behavior
- Importance of Smooth Scroll in CSS
- How Does Smooth Scroll in CSS Work?
- What is CSS scroll-behavior?
- How to Implement Smooth Scroll in CSS?
- Browser Compatibility of CSS scroll-behavior
- Smooth Scroll With JavaScript
- Smooth Scrolling and Accessibility
- Best Practices for Adding Smooth Scroll in CSS
- Frequently Asked Questions (FAQs)
Understanding Browser Scroll Behavior
When you view a web page, you can scroll up and down to navigate its content or click on a link to go directly to a particular section of the page. By default, browsers use instant or jumpy scrolling, which has no default built-in user settings to eliminate this effect.
This means that when you scroll through the content or click on a link, the browser moves quickly from one section of the web page to another, with no gradual transition. This default approach may feel abrupt, particularly when switching between sections of a web page.
Consider a smoother and more elegant way of navigating a web page. This is where smooth scroll in CSS comes into play. When the scroll-behavior property is enabled, the browser adds a touch of elegance to your scrolling experience.
1 2 3 |
.scroll-element { scroll-behavior: scroll; } |
By eliminating abrupt jumps, users can seamlessly transition between sections, reaching their desired content faster and with a more intuitive experience.
Importance of Smooth Scroll in CSS
Beyond aesthetics, smooth scrolling holds significant value for developers and designers. Here are some of the benefits of implementing smooth scrolling on your website.
Smooth scrolling increases user engagement by encouraging users to explore further content and spend more time on your website. This, in turn, reduces the bounce rate, indicating that people value your content while simultaneously sending a positive SEO signal.
Furthermore, websites focusing on the user experience by including smooth scrolling are frequently seen as more modern, aligning with current web design trends. These positive perceptions can help to increase user satisfaction and possibly lead to prolonged user engagement.
To summarize, a smooth scroll in CSS significantly impacts a website’s usability and aesthetics. It contributes greatly to positive user interactions and impressions by providing a more comfortable and visually appealing navigational experience. Additionally, a smooth scroll in CSS can be seamlessly implemented with React. To integrate smooth scrolling with React, you can refer to this Stack Overflow thread.
How Does Smooth Scroll in CSS Work?
Smooth scrolling can be implemented using CSS and, in some instances, JavaScript.
It is particularly beneficial for long-scrolling pages or websites with multiple sections, as it reduces the perceived load on the user and provides a superlative and distraction-free feel to the navigation. Consider a LambdaTest Blog page as an example.
The image above demonstrates how a smooth scroll in CSS makes navigation more enticing. Clicking on the links on the right side of the page takes you to a certain section of the blog with a smooth transition.
It has become a standard necessity in modern web design, contributing to creating user interfaces that prioritize aesthetics and ease of use.
A smooth scroll in CSS improves the way users engage with your websites. Instead of abrupt movement, content glides into view, resulting in a smoother transition between sections. This controlled and consistent scrolling speed improves navigation while preventing abrupt shifts that could disrupt the flow. When implementing smooth scroll in CSS, always remember to consider accessibility.
What is CSS scroll-behavior?
The CSS scroll-behavior property controls the scrolling behavior of an element’s content. It allows developers to customize the speed and vertical movement of scrolling within a certain container.
This property takes in two main values, which are auto and smooth.
auto
This is the scroll-behavior property’s default value. When set to auto, the browser reverts to its default scrolling behavior. When a scroll event or an anchor link is triggered, this usually causes an abrupt and instant scroll to the specified section.
1 2 3 4 |
/* Using auto (default behavior) */ .element-auto { scroll-behavior: auto; } |
smooth
When the CSS scroll-behavior property is set to smooth, it enables a smooth scrolling action. Scrolling becomes animated and gradual. Instead of jumping directly to the target location, the browser slowly transitions the scroll, resulting in a smooth effect. This is especially important for giving users a more comfortable and refined scrolling experience.
1 2 3 |
.element-smooth { scroll-behavior: smooth; } |
We also have other global values, which include:
Values | Description |
---|---|
inherit | Takes the scroll-behavior value from its parent element to ensure uniformity inside a nested structure. |
initial | Sets the scroll-behavior property to its default value, usually equivalent to auto. In most browsers, auto indicates abrupt scrolling between elements. |
revert | Resets the scroll-behavior property to the computed value, which considers all inherited styles and browser defaults. It is most useful when overriding multiple levels of inheritance. |
unset | Removes the scroll-behavior property declaration altogether, falling back to inherited styles or browser defaults |
With these additional values, you now have flexible options for customizing smooth scrolling behavior in CSS.
How to Implement Smooth Scroll in CSS?
In this section, we’ll see how to incorporate smooth scroll in CSS into your website. From creating the basic HTML structure to using the scroll-behavior property in CSS, each major step will be clearly explained for easy understanding.
To achieve this, you’ll need the following:
- Understand how to create a simple HTML document with tags such as <html>, <head>, <body>, and various content elements.
- Understanding CSS syntax, selectors, properties, and how to link a CSS file to an HTML document.
- Access to a text editor or Integrated Development Environment (IDE). Visual Studio Code is preferable.
- A web browser for previewing and testing the smooth scrolling implementation.
We’ll look at two instances of implementing smooth scroll in CSS on a website.
Smooth Scroll in CSS on the Landing Page
First, we’ll see how a smooth scroll in CSS can make a landing page look better. Landing pages are crucial for capturing leads and conversions and show various information divided into various sections, each dedicated to a particular piece of content or point of view. Navigating between these sections can significantly influence user engagement.
Open your code editor, create an HTML file (index.html), and add the following code:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Smooth Scroll in CSS</title> </head> <body> <!-- Navigation Menu --> <nav> <div class="logo-container"> <img src="https://www.lambdatest.com/resources/images/logos/logo.svg" alt="Logo"> </div> <div class="menu-bar"> <i class="fa fa-bars fa-2x" style="color: black;"></i> </div> <div class="nav-links"> <a href="#automation">Automation</a> <a href="#about">About</a> <a href="#testing">Testing</a> </div> <div class="nav-buttons"> <button class="upgrade">Upgrade</button> <button class="book-a-demo">Book a Demo</button> </div> </nav> <!-- Automation Section --> <section id="automation" class="automation-section"> <div class="automation-text-container"> <h2>Online Selenium Test Automation on Desktop, Android, and iOS Mobile Browsers</h2> <p>Run your Selenium test automation scripts across online Selenium Grid of desktop, Android and iOS mobile browsers. Develop, test, and deliver faster every time with automated cross-browser testing using LambdaTest online Automation Browser Testing Grid.</p> <button>Get Started <i class="fa fa-arrow-right"></i></button> </div> <div class="automation-image-container"> <img src="https://www.lambdatest.com/resources/images/selenium-parallel-testing-index.png" alt="Automation"> </div> </section> <!-- About Section 2 --> <section id="about" class="about-section"> <div class="about-text-section"> <h2>More Reasons To Love LambdaTest</h2> <p>Along with 3000+ browser and devices combinations to test we provide you additional features to make sure you give your users a perfect experience. </p> </div> <div class="grid"> <div class="grid-card"> <div class="card-image-container"> <img src="https://www.lambdatest.com/resources/images/headset.svg" alt="headset"> </div> <div class="card-text-container"> <h3>24/7 Support</h3> <p>Got a question? Throw them to our in-app customer chat support or email us on support@lambdatest.com</p> </div> </div> <div class="grid-card"> <div class="card-image-container"> <img src="https://www.lambdatest.com/resources/images/Integration-logo.svg" alt="Integration"> </div> <div class="card-text-container"> <h3>Third-Party Integrations</h3> <p>With a single click, push bugs in your choice of project management tools, directly from LambdaTest platform.</p> </div> </div> <div class="grid-card"> <div class="card-image-container"> <img src="https://www.lambdatest.com/resources/images/header/LambdaTest-Documentation.svg" alt="Documentation"> </div> <div class="card-text-container"> <h3>24/7 Support</h3> <p>Step-by-step documentation for various test automation frameworks to help you run your first Selenium script.</p> </div> </div> </div> </section> <!-- Testing --> <section id="testing" class="testing-section"> <div class="testing-text-container"> <h2>Real Device Cloud for Reliable Mobile App Testing</h2> <p>Test your native hybrid of web mobile apps using LambdaTest's online real device cloud and virtual mobile device platform of emulators and simulators. Eliminating your in-house device labs and bring high scalability to your mobile app testing.</p> <button>See More <i class="fa fa-arrow-right"></i></button> </div> <div class="testing-image-container"> <img src="https://www.lambdatest.com/resources/images/mobile-app-testing.png" alt="Mobile App Testing"> </div> </section> </body> </html> |
This HTML template contains a simple landing page with three sections: automation, about, and testing. Each section has its own navigation link that allows you to navigate between them.
Create a styles.css file and link it to your HTML document. Now, include the following CSS code:
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: sans-serif; padding-top: 80px; height: 100vh; } nav { display: flex; align-items: center; justify-content: space-between; background-color: #fff; box-shadow: 0 0 4px #f5f5f5; padding: 20px 50px; position: fixed; width: 100%; left: 0; top: 0; z-index: 10; } .menu-bar { display: none; } .nav-links { display: flex; justify-content: center; align-items: center; gap: 30px; } a { text-decoration: none; color: #000; font-weight: 500; font-size: 16px; } .nav-buttons { display: flex; gap: 30px; } .upgrade { padding: 10px 15px; border: 1px solid black; border-radius: 0.25rem; cursor: pointer; background-color: #fff; color: black; } .book-a-demo { padding: 12px 15px; border: none; border-radius: 0.25rem; cursor: pointer; color: #fff; background: linear-gradient(91.88deg,#2c57f3 .88%,#a506d8 98.71%); } @media only screen and (max-width: 768px) { body { height: auto; } nav { display: flex; padding: 30px 20px; } .logo-container img { height: 40px; } .menu-bar { display: block; cursor: pointer; } .nav-links { display: none; } .nav-buttons { display: none; } } /* AUTOMATION SECTION */ .automation-section { display: flex; align-items: flex-start; gap: 30px; background-color: rgba(242,242,242); padding: 50px; } .automation-text-container { width: 60%; padding-top: 20px; height: 100%; } .automation-text-container h2 { font-size: 36px; font-weight: 600; margin-bottom: 25px; } .automation-text-container p { font-size: 20px; font-weight: 400; margin-bottom: 30px; } .automation-text-container button { display: flex; align-items: center; gap: 10px; font-size: 20px; color: rgba(14,186,197); font-weight: 600; border: none; background: none; } .automation-image-container { width: 100%; display: flex; } .automation-image-container img { max-width: 100%; height: auto; } @media only screen and (max-width: 992px) { .automation-image-container { display: none; } .automation-text-container { display: flex; flex-direction: column; align-items: center; gap: 30px; width: 100%; padding-top: 20px; height: 100%; } .automation-text-container h2, .automation-text-container p { text-align: center; } .automation-text-container button { font-size: 20px; color: rgba(14,186,197); font-weight: 600; border: none; background: none; } } /* ABOUT SECTION */ .about-section { background-color: rgb(238,245,255); padding: 80px 50px; display: flex; flex-direction: column; align-items: center; } .about-text-section { max-width: 80%; } .about-text-section h2 { margin-bottom: 10px; text-align: center; font-weight: 700; font-size: 40px; } .about-text-section p { text-align: center; font-size: 18px; font-weight: 400; } .grid { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 15px; margin-top: 50px; max-width: 80%; } .grid-card { text-align: center; padding: 30px; background-color: #fff; border-radius: 5px; cursor: pointer; transform: translateY(0); transition: .5s; } .grid-card:hover { transform: translateY(-15px); } .card-image-container { width: 100px; margin: 0 auto; margin-bottom: 55px; } .card-image-container img { max-width: 100%; height: auto; } .card-text-container h3 { margin-bottom: 24px; font-size: 20px; font-weight: 600; } .card-text-container p { font-size: 16px; } @media only screen and (max-width: 992px) { .grid { grid-template-columns: repeat(2, 1fr); grid-gap: 20px; } } @media only screen and (max-width: 768px) { .about-section { padding: 80px 20px; } .grid { grid-template-columns: 1fr; } } /* Testing */ .testing-section { display: flex; flex-direction: row-reverse; align-items: flex-start; gap: 30px; background-color: #fff; padding: 50px; } .testing-text-container { width: 60%; padding-top: 20px; height: 100%; } .testing-text-container h2 { font-size: 36px; font-weight: 600; margin-bottom: 25px; } .testing-text-container p { font-size: 20px; font-weight: 400; margin-bottom: 30px; } .testing-text-container button { display: flex; align-items: center; gap: 10px; font-size: 20px; color: rgba(14,186,197); font-weight: 600; border: none; background: none; } .testing-image-container { width: 100%; display: flex; } .testing-image-container img { max-width: 100%; height: auto; } @media only screen and (max-width: 992px) { .testing-image-container { display: none; } .testing-text-container { display: flex; flex-direction: column; align-items: center; gap: 30px; width: 100%; padding-top: 20px; height: 100%; } .testing-text-container h2, .testing-text-container p { text-align: center; } .testing-text-container button { font-size: 20px; color: rgba(14,186,197); font-weight: 600; border: none; background: none; } } |
We’ve added some styling to the landing page. Let’s add the scroll-behavior property with various values to test how the web page behaves when scrolling.
auto
Most browsers default to an auto value for the scroll-behavior property, resulting in sudden jumps when scrolling between elements.
1 2 3 4 |
html { scroll-behavior: auto; } /* Add your additional styling. */ |
If you visit this website in a browser, you will see that the sections are stacked vertically. Clicking on the links in the navbar (provided they link to the appropriate section IDs) will instantly jump to the desired section. This can seem unsettling, especially if sections are long.
Output:
The page jumps straight to the desired section when a link is clicked, which is an average user experience. A smooth scroll in CSS shines here, eliminating the instant jump between sections.
Smooth scroll in CSS allows users to effortlessly navigate between sections, improving the flow of information and retaining focus.
See the Pen
Landing Page without Smooth Scroll by Chosen (@Chosen-the-vuer)
on CodePen.
value
We will add smooth value to make the experience more seamless and engaging. Still, in styles.css, remove the auto value and replace it with smooth to enable smooth scrolling.
1 2 3 4 5 |
html { scroll-behavior: smooth; } /* Add your additional styling. */ |
Now that we’ve changed the scroll-behavior value to smooth, let’s see the scroll experience.
Output:
The above output shows the smooth scroll effect achieved with just a single line of CSS code! This simple yet effective property can substantially improve the usability of your landing page and create a positive first impression for your visitors.
See the Pen
Landing Page Smooth Scroll by Chosen (@Chosen-the-vuer)
on CodePen.
You can use this interactive example to see the difference between the smooth and auto values for yourself. It’s inspired by Rik Schennink’s CodePen work. This sample lets you play with both options and see how they affect scrolling behavior.
See the Pen
Scroll and Auto by Chosen (@Chosen-the-vuer)
on CodePen.
Smooth Scroll in CSS on the Blog Page
The second scenario we’ll look at is a blog page. Blogs are valuable sources of information, but accessing long content may be time-consuming, particularly on mobile devices.
Scrolling through vast amounts of content can be overwhelming and reduce user engagement. This is where smooth scroll in CSS comes in, providing a solution for improving the reading experience on blog pages.
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title>CSS Smooth Scroll</title> </head> <body> <nav> <a href="https://www.lambdatest.com/"> <div class="logo-container"> <img src="https://www.lambdatest.com/resources/images/logos/logo.svg" alt="Logo"> </div> </a> <div class="menu-bar"> <i class="fa fa-bars fa-2x" style="color: black;"></i> </div> <div class="nav-links"> <a href="#about">Home</a> <a href="#browser-testing">About</a> <a href="#real-device-testing">Blog</a> </div> <div class="nav-buttons"> <button class="upgrade">Upgrade</button> <button class="book-a-demo">Book a Demo</button> </div> </nav> <main> <div class="blog-heading"> <h1>What is Cross-Device Testing: Why and How to Perform It? </h1> <p>In this tutorial, learn cross-device testing, its key concepts, significance, and techniques for performing cross-device testing. .</p> </div> <ul> <li class="list-title">On This Page</li> <li><a href="#overview">Overview</a></li> <li><a href="#why-cross-device-testing">Why Do We Need Cross Device Testing?</a></li> <li><a href="#where-to-run-cross-device-test">Where to Run Cross Device Tests?</a></li> <li><a href="#cross-device-testing-on-the-cloud">Cross Device Testing on the Cloud</a></li> </ul> <section id="overview" class="blog-container"> <h2>Overview</h2> <p>Cross device testing is the process that involves evaluating the functionality, usability, and visual uniformity of mobile applications on different types of devices. Its main objective is to ensure a consistent user experience, no matter which device is in use. This testing method considers differences in screen sizes, resolutions, device types, and operating systems, among other variables.</p> <p>Considering such variables in the test process is important to ensure a seamless user experience across different devices in the market. If we look at the statistics, by 2025, the number of mobile devices is expected to reach 18.22 billion, indicating an increase of 4.2 billion devices compared to 2020. In 2022, the global count of smartphone mobile network subscriptions reached 6.4 billion; forecasts project it to exceed 7.7 billion by 2028.</p> <div class="blog-image-container"> <img src="https://www.lambdatest.com/resources/images/learning-hub/online-content-through-mobile-devices-stat.webp" alt="Chart"> </div> </section> <section id="why-cross-device-testing" class="blog-container"> <h2>Why Do We Need Cross-Device Testing?</h2> <p>The need for cross-device testing in this digital landscape is due to the availability of a vast range of devices and operating systems that users use to access software applications.</p> <p>TAs per Statista, in December 2022, most mobile devices sold were smartphones, making up 77% of the market share, followed by Smart tablets (11.5%) and Smart wearables (8.1%), signifying the importance of cross-device testing based on device types.</p> <div class="blog-image-container"> <img src="https://www.lambdatest.com/resources/images/learning-hub/most-mobile-devices-sold-stat.webp" alt="Chart"> </div> </section> <section id="where-to-run-cross-device-test" class="blog-container"> <h2>Where to Run Cross Device Tests?</h2> <p>The need for cross-device testing in this digital landscape is due to the availability of a vast range of devices and operating systems that users use to access software applications. </p> <p>TAs per Statista, in December 2022, most mobile devices sold were smartphones, making up 77% of the market share, followed by Smart tablets (11.5%) and Smart wearables (8.1%), signifying the importance of cross-device testing based on device types.</p> <div class="blog-image-container"> <img src="https://www.lambdatest.com/resources/images/native_cta.png" alt="Chart"> </div> </section> <section id="cross-device-testing-on-the-cloud" class="blog-container"> <h2>Cross Device Testing on the Cloud</h2> <p>To perform mobile application testing across multiple devices, managing the infrastructure of the latest devices, operating systems, browsers, and their respective versions becomes essential. This can be quite cumbersome, demanding a dedicated team for effective management, not to mention its considerable financial overhead. Furthermore, the process is time-intensive and often encounters scalability issues.</p> <p>During real device cloud testing, you can access essential debugging tools such as network logs, device logs, app logs, videos, and screenshots, providing comprehensive insights into your app's performance. Testing your apps is a breeze - simply upload the .abb, .apk, or .ipa files. You can also install production apps directly from the Google Play Store or App Store.</p> <div class="blog-image-container"> <img src="https://www.lambdatest.com/resources/images/learning-hub/real-device-from-the-left-sidebar-menu-on-lambdatest.webp" alt="Chart"> </div> </section> </main> </body> </html> |
This HTML code is the foundation for our blog post example of smooth scroll in CSS. Let us break down the important elements:
- Navigation (nav): This section includes the website’s logo, menu bar, navigation links, and buttons.
- Main Content (main): This section contains the blog post’s primary content, such as the header, section list, and numerous content sections.
- Sections (section): Each section contains particular content relating to various topics inside the blog post, identifiable by unique IDs.
- List (ul): This list contains links to various portions of the blog post, letting viewers navigate straight to certain parts.
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
* { margin: 0; padding: 0; box-sizing: border-box; } html { scroll-behavior: smooth; } body { font-family: sans-serif; padding-top: 80px; background-color: #fff; } nav { display: flex; align-items: center; justify-content: space-between; background-color: #fff; box-shadow: 0 0 4px #f5f5f5; padding: 20px; position: fixed; width: 100%; left: 0; top: 0; z-index: 10; } .nav-links, .nav-buttons { display: none; } main { padding: 50px 20px; width: 100%; } .blog-heading { margin-bottom: 30px; font-size: 16px; color: #4a4a4a; } .blog-heading > h1 { font-size: 36px; font-weight: 700; margin-bottom: 10px; } ul { margin-bottom: 30px; background-color: #f5f5f5; border-radius: 4px; padding: 20px; } ul li { list-style-type: none; margin-bottom: 15px; } .list-title { text-transform: uppercase; border-bottom: 1px solid #7e7b7b; padding-bottom: 15px; font-weight: 600; } a { text-decoration: none; color: #4a4a4a; font-weight: 500; } ul li a:hover { color: blue; } /* BLOG CONTENT SECTION */ .blog-container { margin-bottom: 50px; } .blog-container > h2 { font-size: 36px; font-weight: 600; margin-bottom: 25px; } .blog-container > p { margin-bottom: 25px; line-height: 28px; } .blog-image-container { display: flex; justify-content: center; } .blog-image-container > img { max-width: 100%; height: auto; } |
This CSS code styles various elements on the blog page while introducing the scroll-behavior property, whose value is smooth for seamless scrolling.
Output:
I used LT Browser to check the responsiveness of mobile layouts.
LT Browser is a mobile site tester that simplifies responsive testing across several screen sizes and resolutions, providing developers and testers with a seamless experience for previewing and debugging websites.
Responsive design is of the utmost importance. With an increasing number of different devices and screen sizes, ensuring that your website adapts seamlessly to different viewports is important for offering the best user experience.
We’ll use media queries for standard devices to apply different styles depending on screen width, ensuring responsiveness. For example, we can change text sizes, layout structures, and navigation menus to fit different screens while maintaining usability.
6. Media queries
Media queries allow you to apply different styles based on the characteristics of the user's device.
For example, you can use a media query to apply a different layout for users on a small screen, or to hide certain elements on a mobile device.— Ailín Tobin (@tobinthe2nd) December 7, 2022
CSS code with a media query:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
@media only screen and (min-width: 992px) { .menu-bar { display: none; } .nav-links { display: flex; justify-content: center; align-items: center; gap: 30px; } .nav-buttons { display: flex; gap: 30px; } .upgrade { padding: 10px 15px; border: 1px solid black; border-radius: 0.25rem; cursor: pointer; background-color: #fff; color: black; } .book-a-demo { padding: 12px 15px; border: none; border-radius: 0.25rem; cursor: pointer; color: #fff; background: linear-gradient(91.88deg, #2c57f3 0.88%, #a506d8 98.71%); } main { max-width: 65%; margin-left: 50px; } ul { position: fixed; right: 10px; top: 150px; max-width: 30%; max-height: 350px; overflow-y: auto; } ul li { margin-bottom: 15px; } } @media only screen and (min-width: 1500px) { nav { padding: 20px 50px; } main { max-width: 75%; margin-left: 50px; } } |
On larger displays, the navigation bar is fixed, and the list of section links is positioned to the right for quick access.
Output:
As can be seen from the above example, implementing a smooth scroll in CSS can help users navigate your content more effectively. This creates a more delightful and interesting reading experience, enabling users to navigate easily.
See the Pen
Blog Page Smooth Scroll by Chosen (@Chosen-the-vuer)
on CodePen.
Browser Compatibility of CSS scroll-behavior
The scroll-behavior property is a reliable method to enable a smooth scroll in CSS. It is widely supported by modern browsers, which eliminates compatibility problems. However, it is still crucial to consider the browsing trends of your target audience and provide a consistent experience across multiple platforms.
The image above shows that while the scroll-behavior property is widely supported, it may have limitations in specific older browsers. Try using alternate smooth scrolling technologies or JavaScript-based options to ensure maximum compatibility.
Also, to ensure browser compatibility of your scroll behavior, you can leverage cloud-based testing platforms like LambdaTest.
It is an AI-powered test orchestration and execution platform that lets you perform live-interactive browser testing on a remote test lab of different browsers, devices, and operating systems. With LambdaTest, you can test scroll behavior on the latest and legacy web browsers online. This includes testing on Chrome browser online, Firefox browser online, Microsoft Edge online, Internet Explorer online, and more.
Subscribe to the LambdaTest YouTube Channel. Get real-time updates on various automation testing tutorials covering Selenium, automation testing, and more.
Smooth Scroll With JavaScript
While scroll-behavior: smooth property can be used to add a basic smooth scroll in CSS, JavaScript allows more precise control and flexibility.
In this section, we’ll look at achieving smooth scrolling with JavaScript, continuing from the landing page example we explored earlier. We’ll look at the navigation links container within the navigation bar (<nav></nav>).
HTML:
1 2 3 4 5 |
<div class="nav-links"> <a href="#about">About</a> <a href="#browser-testing">Browser Testing</a> <a href="#real-device-testing">Real Device Testing</a> </div> |
Each anchor tag (<a>) contains a href element that specifies the ID of the linked section. For example, clicking the About link (<a href=”#about”>About</a>) will smoothly scroll to the section with the ID about.
JavaScript:
Create a script.js file or place the JavaScript code within a <script> tag at the end of your HTML file, just before the closing </body> tag.
1 2 3 4 5 6 7 8 9 10 11 12 |
const navLink = document.querySelectorAll('.nav-links a'); navLink.forEach(link => link.addEventListener('click', smoothScroll)); function smoothScroll(event){ event.preventDefault(); const targetId = event.currentTarget.getAttribute("href"); window.scrollTo({ top: document.querySelector(targetId).offsetTop, behavior: "smooth" }) } |
Let’s break down the JavaScript code that enables smooth scrolling:
Selecting Navigation Links
This line selects all anchor tags (<a>) within the element with the class nav-links (presumably the navigation menu).
Adding Event Listeners
This code iterates through each selected anchor tag and adds a click event listener. When a link is clicked, the smoothScroll function is triggered.
smoothScroll Function
This line prevents the default behavior of anchor tags, which is to abruptly jump to the linked section.
This retrieves the ID of the target section from the clicked link’s href attribute.
This line is the core of the smooth scrolling functionality. It uses the window.scrollTo() method to scroll the page. The top: document.querySelector(targetId).offsetTop calculates the vertical distance (in pixels) from the top of the page to the target section’s top. behavior: “smooth” enables the smooth scrolling animation.
With this code in place, clicking on any navigation link will activate the smoothScroll function, resulting in a smooth transition to the corresponding section on the webpage.
Output:
A significant benefit of utilizing JavaScript over CSS is the ability to adjust the scroll speed to meet specific design needs. Let’s look at how we can leverage this flexibility and customize the scrolling behavior to our needs.
We’ll be working with the existing HTML code from our previous example. Only the JavaScript code will change. You can also view the complete code on CodePen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
const navLink = document.querySelectorAll('.nav-links a'); navLink.forEach(link => link.addEventListener('click', smoothScroll)); function smoothScroll(event) { event.preventDefault(); const targetId = event.currentTarget.getAttribute("href"); const targetElement = document.querySelector(targetId); const startingY = window.scrollY; const targetY = targetElement.offsetTop; const distance = targetY - startingY; let startTime = null; function animate(currentTime) { if (startTime === null) startTime = currentTime; const elapsedTime = currentTime - startTime; // Adjust the timing function and duration for speed control const ease = elapsedTime / 900; // Linear timing // Calculate newY considering both upward and downward scrolling const newY = startingY + ease * distance; window.scrollTo(0, newY); // Continue animation until targetY is reached if ((distance > 0 && newY < targetY) || (distance < 0 && newY > targetY)) { requestAnimationFrame(animate); } } requestAnimationFrame(animate); } |
Here’s a detailed explanation of the JavaScript code for controlling scroll speed:
Selecting Navigation Links
This line uses querySelectorAll to find all anchor tags (a) within an element with the class nav-links. These anchor tags are the navigation links on the webpage.
Adding Click Event Listeners
This line iterates through each navLink (the anchor tags) using a forEach loop. Inside the loop, a click event listener is added to each link. When a link is clicked, the smoothScroll function is triggered.
Preventing Default Behavior
This line (inside the smoothScroll function) prevents the default behavior of anchor tags, which is to jump to the target section abruptly. This allows us to control the scrolling animation instead.
Getting Target Information
The first line retrieves the href attribute of the clicked link (event.currentTarget). The href attribute typically holds the ID of the section the link points to. The second line uses querySelector to find the element on the page that matches the ID retrieved in the previous step. This targetElement is the section you want to scroll through smoothly.
Calculating Scrolling Details
The first line gets the current vertical scroll position of the page using window.scrollY. The second line retrieves the vertical offset (distance from the top) of the targetElement on the page. The third line calculates the total distance (positive or negative) you must scroll to reach the target element.
Creating Animation Loop
The first line declares a variable startTime to keep track of the animation start time. The second line defines an inner function, animate, that’s called repeatedly to create the smooth scrolling animation.
Calculating Animation Progress
The first line calculates the elapsed time since the animation started. The second line calculates the ease value, which controls the speed and smoothness of the animation. A higher value creates a slower animation, and a lower value creates a faster animation.
Calculating New Scroll Position
This line calculates the new vertical scroll position based on the starting position (startingY), the animation progress (ease), and the target distance (distance).
Updating Scroll Position
This line updates the scroll position of the page smoothly to the calculated newY value.
Continuing Animation
This conditional statement checks if the animation has reached the target scroll position yet. Based on the direction (positive or negative distance) and whether newY has crossed the targetY, the animation loop continues using requestAnimationFrame if needed.
Output:
The smooth scrolling animation in the example above appears to be slower because the ease value in the code is set to 900—a higher ease value results in a slower transition. You can change this value to set the appropriate animation speed.
In conclusion, a smooth scroll in CSS is an excellent choice for a quick and straightforward setup. However, JavaScript offers greater flexibility and control when tailoring the animation or targeting certain items.
See the Pen
Smooth Scroll Speed by Chosen (@Chosen-the-vuer)
on CodePen.
Smooth Scrolling and Accessibility
A smooth scroll in CSS can add a touch of polish to your website and improve the user experience. However, it is crucial to consider accessibility when integrating this functionality. Uncontrolled smooth scrolling can pose difficulties for people with impairments.
Users who are sensitive to motion or have vestibular disorders may experience nausea or dizziness due to abrupt or excessive scrolling animations. Fluid scrolling animations may be difficult for individuals who use keyboards to navigate. Excessive or rapid scrolling can impair their ability to focus on certain page components, making it difficult to navigate and retrieve content.
Furthermore, unexpected scrolling motions might break the flow of information for screen reader users, making it difficult to understand the web page layout. To improve accessibility, scrolling animations should not interfere with the screen reader’s ability to comprehend and transmit material properly.
Providing a consistent and predictable scrolling experience can significantly improve the accessibility of your website for all users. To ensure web accessibility, you can use the LambdaTest platform to perform accessibility testing at scale across 3000+ real environments. Plus, you can leverage LambdaTest Accessibility DevTools Chrome extension to run quick and hassle-free accessibility tests.
WCAG Considerations
It is important to ensure smooth scroll implementation follows the Web Content Accessibility Guidelines (WCAG). Consider the following WCAG success criteria to keep smooth scrolling accessible:
- Success Criterion 1.3.1 – Meaningful Movement: When using smooth scroll in CSS, make sure the scrolling animation serves a clear function and does not introduce unnecessary or unexpected movement. Smooth scroll in CSS should improve navigation and content presentation without causing confusion or discomfort for users. – WCAG Info and Relationships.
- Success Criterion 2.1.1 – Keyboard: Smooth scrolling should not disrupt keyboard navigation. Users who rely on keyboard input should be able to move across elements smoothly, tabbing through content without interruption. Ensure that keyboard navigation remains practical and intuitive, in addition to smooth scrolling – WCAG Keyboard Accessible.
- Success Criterion 3.2.1 – Consistent Navigation: A good user experience requires consistency in navigation. Maintain a predictable and consistent focus order while implementing smooth scroll in CSS to guarantee that users can move through the content with ease. Smooth scrolling should not break the logical flow of navigation or cause uncertainty about focus order – WCAG On Focus Level A.
By aligning smooth scrolling with these WCAG success criteria, you can ensure that your website is always accessible to all users, creating a seamless and accessible browsing experience.
Recommendations for Accessible Smooth Scrolling
Here are some suggestions for creating an accessible, smooth scrolling experience for users:
- Consider Accessibility for All Users: A smooth scroll in CSS may have a negative impact on specific disabilities, such as motion sensitivity or vestibular disorders. Users who prefer traditional scrolling behavior may disable smooth scrolling in their browsers with the following steps:
First, open your browser and type chrome://flags. (For other browsers, replace chrome with the browser name, such as edge://flags.). You should see something like this.
After that, search for smooth scrolling in the search box on the screen.
- Use Subtle and Controlled Animations: Use smooth scrolling animations that are moderate and predictable, avoiding excessive movement or rapid changes.
- Maintain Focus During Scrolling: Ensure focus remains on the intended element, even during smooth scrolling transitions. This helps users with keyboard navigation maintain control.
- Test With Assistive Technologies: To detect and address accessibility issues, thoroughly test your implementation using assistive technologies like screen readers and keyboard navigation.
Lastly, you can select the options as either Default, Enabled, or Disabled.
By adhering to these principles and recommendations, you can successfully add smooth scroll functionality that improves the user experience for everyone, including people with disabilities.
Test your smooth scroll in CSS on real devices. Try LambdaTest Today!
Best Practices for Adding Smooth Scroll in CSS
Applying the scroll-behavior: smooth property is not enough to implement a smooth scroll on your webpage. Here are some best practices to ensure a successful and optimized implementation:
Start With Progressive Enhancement
Start with the scroll-behavior: smooth property provided by CSS. This offers a solid foundation. However, consider layering on additional solutions, such as JavaScript-based smooth scrolling. This method allows for greater customization while also ensuring compatibility with a variety of browsers and devices.
Ensure Consistent Section Height and Semantic Elements
Maintaining consistent heights within your scrollable section. Uniform heights contribute to a more predictable scrolling experience. Additionally, leverage semantic HTML elements like <section>, <article>, and <nav> to organize your content. These elements not only enhance accessibility but also create distinct anchor points for smooth scrolling, ensuring a well-structured foundation.
Use Link IDs and Anchor Links
Give your sections meaningful IDs and use anchor links (<a href=”#sectionID”>) for easy navigation. This enables visitors to navigate directly to specified sections of your website, improving user experience and accessibility.
Customize Scroll Speed Using JavaScript
When necessary, use JavaScript to alter the scroll speed. This allows for fine-tuning of the scrolling behavior to correspond with design needs and user preferences.
Optimize Performance
Improve performance by reducing complex animations, especially on resource-intensive pages. Reduce redundant animations to enable smooth scroll in CSS and a positive user experience across all devices and platforms.
Ensure Consistency Across Platforms
Verify the consistency of your smooth scroll implementation across various web browsers and devices. As mentioned earlier in this blog, you can leverage tools like LT Browser by LambdaTest for comprehensive, responsive testing to ensure that all users have a smooth scrolling experience, regardless of device or browser.
Conclusion
In this blog on adding a smooth scroll in CSS, we discovered a simple yet effective approach to improving the user experience on our web pages. A smooth scroll provides a touch of elegance, making CSS transitions between sections more visually appealing and user-friendly.
Remember that successful implementation is more than simply the code; it also requires careful design considerations. A smooth scrolling experience is made possible by semantic HTML, consistent section heights, and fine-tuned scroll behavior. We’ve also prioritized accessibility, progressive enhancement, and documentation to offer a complete and inclusive solution.
As technology advances and user expectations change, the art of seamless scrolling will continue to play an important part in designing future digital experiences.
Frequently Asked Questions (FAQs)
How do I make my CSS scroll smoother?
You can use overflow: scroll with scroll-behavior: smooth on the scrollable element or explore JavaScript libraries for more customization.
What is a smooth scroll?
A smooth scroll is a feature where the website’s content transitions smoothly when scrolling, creating a more pleasant user experience.
How do you smooth scroll between sections in CSS?
You can assign IDs to sections, create anchor links with href=”#section-id”, and apply scroll-behavior: smooth to the anchor links in CSS.
How do you smoothly scroll to the bottom in CSS?
You can link to an anchor at the bottom (e.g., href=”#bottom”) with a smooth scroll applied or use JavaScript to detect and scroll to the bottom smoothly.
Got Questions? Drop them on LambdaTest Community. Visit now