Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a smooth scrolling effect with CSS?
The smooth scrolling effect can be set on a web page using the scroll-behaviour property. Set the value to smooth. Check this by implementing scrolling effect on the click of buttons i.e., reaching the below section by clicking a button the top, and vice versa. Let us see how to create a smooth scrolling effect with HTML and CSS.
Smooth scrolling for the web page
To begin with, under the <html>, set the scroll-behaviour property to implement the property for thr entire web page −
html {
scroll-behavior: smooth;
}
Set the two sections
The two sections are set as two separate divs. One at the top and another below the 1st section −
<div id="firstSection"> <h2>Top</h2> <a href="#secondSection">Click Here to Smooth Scroll Below</a> </div> <div id="secondSection"> <h2>Bottom</h2> <a href="#firstSection">Click Me to Smooth Scroll Above</a> </div>
Style the top section
The 1st section is set with height 100vh −
#firstSection {
height: 100vh;
background-color: rgb(119, 77, 219);
color: white;
padding: 20px;
}
Style the bottom section
The bottom section is just below the 1st section. The same property value is set for this section as well for the height −
#secondSection {
height: 100vh;
color: white;
background-color: rgb(42, 128, 168);
padding: 20px;
}
Example
To create a smooth scrolling effect with CSS, the code is as follows −
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
* {
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0px;
padding: 0px;
}
h2 {
text-align: center;
}
#firstSection {
height: 100vh;
background-color: rgb(119, 77, 219);
color: white;
padding: 20px;
}
#secondSection {
height: 100vh;
color: white;
background-color: rgb(42, 128, 168);
padding: 20px;
}
a {
text-decoration: none;
font-size: 20px;
font-weight: bold;
color: yellow;
background-color: black;
}
</style>
</head>
<body>
<h1>Smooth Scroll Example</h1>
<div id="firstSection">
<h2>Top</h2>
<a href="#secondSection">Click Here to Smooth Scroll Below</a>
</div>
<div id="secondSection">
<h2>Bottom</h2>
<a href="#firstSection">Click Me to Smooth Scroll Above</a>
</div>
</body>
</html>