Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a smooth scrolling effect with CSS?
The smooth scrolling effect can be created on a web page using the CSS scroll-behavior property. This property controls the scrolling behavior when users click on anchor links, providing a smooth transition instead of an instant jump to the target section.
Syntax
html {
scroll-behavior: smooth;
}
Possible Values
| Value | Description |
|---|---|
auto |
Default instant scrolling behavior |
smooth |
Smooth animated scrolling behavior |
Example: Creating Smooth Scrolling Between Sections
The following example demonstrates smooth scrolling between two sections using anchor links −
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin: 20px 0;
}
.section {
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 20px;
color: white;
}
#firstSection {
background-color: #774dd9;
}
#secondSection {
background-color: #2a80a8;
}
.scroll-link {
background-color: #000;
color: #ffff00;
padding: 10px 20px;
text-decoration: none;
border-radius: 5px;
font-weight: bold;
margin-top: 20px;
}
.scroll-link:hover {
background-color: #333;
}
</style>
</head>
<body>
<h1>Smooth Scroll Example</h1>
<div id="firstSection" class="section">
<h2>Top Section</h2>
<p>This is the first section of the page.</p>
<a href="#secondSection" class="scroll-link">Click to Scroll Down</a>
</div>
<div id="secondSection" class="section">
<h2>Bottom Section</h2>
<p>This is the second section of the page.</p>
<a href="#firstSection" class="scroll-link">Click to Scroll Up</a>
</div>
</body>
</html>
A page with two full-height colored sections. The first section has a purple background with a yellow button to scroll down, and the second section has a blue background with a yellow button to scroll up. Clicking the buttons creates a smooth animated scroll transition between sections.
Key Points
- Apply
scroll-behavior: smoothto thehtmlelement to affect the entire page - Works with anchor links that reference elements with
idattributes - The smooth scrolling effect is automatic when users click anchor links
- Browser support is good for modern browsers, with fallback to instant scrolling
Conclusion
The CSS scroll-behavior: smooth property provides an easy way to enhance user experience with animated scrolling. Simply apply it to the html element and use anchor links to create smooth transitions between page sections.
Advertisements
