Smooth Scrolling Compatible with All Browsers
Smooth scrolling is a popular web design technique that improves the user experience by providing a smooth and effortless scrolling effect. In this blog post, we’ll explore how to implement smooth scrolling using both CSS and JavaScript.
Smooth Scrolling with CSS
CSS provides an easy way to achieve smooth scrolling by using the scroll-behavior
property. This property allows you to control the scrolling behavior of a webpage. To enable smooth scrolling on your webpage, you can set the scroll-behavior
property to smooth
in your CSS code.
html {
scroll-behavior: smooth;
}
This code will enable smooth scrolling for the entire webpage.
Note that not all browsers support the scroll-behavior
property. If you want to ensure cross-browser compatibility, you’ll need to use JavaScript.
Smooth Scrolling with JavaScript
JavaScript provides a more robust way to implement smooth scrolling that works across all browsers. To achieve smooth scrolling with JavaScript, you’ll need to use JavaScript method and some math.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
});
</script>
Conclusion
Smooth scrolling is a great way to enhance the user experience on your website. By using CSS or JavaScript, you can achieve a smooth and effortless scrolling effect that will make your website feel more polished and professional.