How to Make Smooth Scrolling Using Only CSS
If you want some smooth scrolling to happen without using an algorithm, you can use the CSS scroll-behavior
property:
Copied to clipboard! Playground
<!-- Set the `scroll-behavior` property to create smooth scrolling -->
<style>
html {
scroll-behavior: smooth;
}
</style>
<nav>
<a href="#page-1">Scroll to page #1</a>
<a href="#page-2">Scroll to page #2</a>
<a href="#page-3">Scroll to page #3</a>
</nav>
<section id="page-1">Page #1</section>
<section id="page-2">Page #2</section>
<section id="page-3">Page #3</section>
Keep in mind this is only supported for modern browsers. You can check the working example at Codepen:
Check Smooth Scrolling on Codepen
If you want a JavaScript-based solution with a little bit more support, you can use the behavior
option in window.scroll
:
Copied to clipboard! Playground
// JavaScript equivalent for smooth scrolling
window.scroll({
top: 100,
left: 0,
behavior: 'smooth'
});
Resources:
π More Webtips
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:
Courses
CSS - The Complete Guide (including Flexbox, Grid and Sass)
Including Flexbox, Grid, and Sass
Whether you're learning CSS for the first time or brushing up on your CSS skills and diving even deeper, this course is for you. Every web developer has to know CSS.
The HTML & CSS Bootcamp
From Zero to Expert!
This course covers flexbox, CSS grid, animations, responsive design, and much more! You will find tons of exercises & projects inside this course.
The Creative HTML5 & CSS3 Course
Build Awesome Websites
Learn HTML5 and CSS3 by creating three amazing, well-designed and animated websites from scratch.