You can use CSS, JavaScript or a JavaScript library, like jQuery, to create a smooth-scrolling solution that will work for all browsers.
This article learns you how to create a smooth-scrolling effect with CSS.
1. Create an HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML5+CSS-Smooth scrolling</title>
<meta charset="UTF-8" />
<meta name="author" content="PhDr. Matej Lednár, PhD." />
<style>
section {
background-color: rgba(165, 42, 42, 1);
height: 100vh;
padding: 30%;
font-size: 4rem;
}
li {
list-style: none;
display: inline-block;
padding: 0 2rem;
}
</style>
</head>
<body>
<nav>
<ul>
<li><a href="#section_1">Section 1</a></li>
<li><a href="#section_2">Section 2</a></li>
<li><a href="#section_3">Section 3</a></li>
</ul>
</nav>
<section id="section_1">Section 1</section>
<section id="section_2" style="opacity: 0.7">Section 2</section>
<section id="section_3" style="opacity: 0.4">Section 3</section>
</body>
</html>
2. Use scroll-behavior: smooth
;.
.smooth-scrolling {
scroll-behavior: smooth;
}
3. Add .smooth-scrolling
class to the <html> element to enable smooth scrolling for the whole page.
<html lang="en" class="smooth-scrolling">
Final example.
<!DOCTYPE html>
<html lang="en" class="smooth-scrolling">
<head>
<title>HTML5+CSS-Smooth scrolling</title>
<meta charset="UTF-8" />
<meta name="author" content="PhDr. Matej Lednár, PhD." />
<style>
.smooth-scrolling {
scroll-behavior: smooth;
}
section {
background-color: rgba(165, 42, 42, 1);
height: 100vh;
padding: 30%;
font-size: 4rem;
}
li {
list-style: none;
display: inline-block;
padding: 0 2rem;
}
</style>
</head>
<body>
<nav>
<ul>
<li><a href="#section_1">Section 1</a></li>
<li><a href="#section_2">Section 2</a></li>
<li><a href="#section_3">Section 3</a></li>
</ul>
</nav>
<section id="section_1">Section 1</section>
<section id="section_2" style="opacity: 0.7">Section 2</section>
<section id="section_3" style="opacity: 0.4">Section 3</section>
</body>
</html>
Conclusion
The scroll-behavior property specifies the scrolling behavior for a scrolling box, when scrolling happens due to navigation, scrolling APIs [CSSOM-VIEW], or scroll snapping operations not initiated by the user [CSS-SCROLL-SNAP-1]. Any other scrolls, e.g. those that are 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.
The scroll-behavior property of the HTML body
element is not propagated to the viewport. When you use the smooth
value, the scrolling box is scrolled in a smooth fashion using a user-agent-defined timing function over a user-agent-defined period of time. User agents should follow platform conventions, if any.