CSS Properties
CSS scroll-behavior Property
Photo Credit to CodeToFun
🙋 Introduction
The scroll-behavior
property in CSS is used to control the scrolling behavior for a webpage.
This property specifies whether to use smooth scrolling or instant scrolling when a user navigates through internal links within a document or when a script calls for scrolling. Smooth scrolling provides a visually appealing and user-friendly experience, especially for single-page applications and websites with long content.
💡 Syntax
The syntax for the scroll-behavior
property is simple. It can be applied to the html element to affect the entire document, or to any scrollable container.
element {
scroll-behavior: value;
}
🎛️ Default Value
The default value of the scroll-behavior
property is auto, which provides an instant scrolling effect.
🏠 Property Values
Value | Description |
---|---|
auto | This value provides instant scrolling, the default behavior. |
smooth | This value enables smooth scrolling, creating a gradual scrolling effect. |
📄 Example
In this example, we'll enable smooth scrolling for the entire webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS scroll-behavior Example</title>
<style>
html {
scroll-behavior: smooth;
}
section {
height: 100vh;
padding: 20px;
}
</style>
</head>
<body>
<h1>Smooth Scrolling Example</h1>
<nav>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</nav>
<section id="section1" style="background-color: lightcoral;">Section 1</section>
<section id="section2" style="background-color: lightblue;">Section 2</section>
<section id="section3" style="background-color: lightgreen;">Section 3</section>
</body>
</html>
🖥️ Browser Compatibility
The scroll-behavior
property is supported in most modern browsers, including the latest versions of Chrome, Firefox, and Edge. Safari currently has limited support, so it's important to test this property across different browsers to ensure compatibility.
🎉 Conclusion
The scroll-behavior
property is a useful tool for enhancing user experience by providing smooth scrolling effects on your website.
By applying this property, you can make navigating long pages or single-page applications more visually appealing and user-friendly. Experiment with this property to see how it can improve the navigation and overall feel of your web projects.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS scroll-behavior Property), please comment here. I will help you immediately.