Smooth Scroll in CSS
In this blog, we will learn how to create a smooth scroll via CSS. Sometimes there is a need to create a smooth scroll on a website, mostly when we have a single page website and want to move to a particular section on click of the anchor tag.
We can create a smooth scroll by using pure CSS code there is no need for Javascript or jQuery. Let’s see how we can do this:
You have to write the following code in your CSS file:
html {
scroll-behavior: smooth;
}
Example:
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
.main
{
width:100%;
height:2000px;
background:#ddd;
}
.menu
{
width:100%;
height:100px;
background:#ddd;
}
.section
{
width:100%;
height:300px;
background:#f00;
margin:100px 0;
}
</style>
</head>
<body>
<div class="main">
<div class="menu">
<a href="#section1">section1</a>
<a href="#section2">section2</a>
<a href="#section3">section3</a>
<a href="#section4">section4</a>
</div>
<div class="section" id="section1">
section1
</div>
<div class="section" id="section2">
section2
</div>
<div class="section" id="section3">
section3
</div>
<div class="section" id="section4">
section4
</div>
</div>
</body>
</html>