Smooth Scrolling with CSS and Anchors
In the pursuit of creating a seamless user experience, you may desire to implement smooth scrolling upon clicking a button at the top of a page. While a CSS-only solution is available, involving input buttons, we explore an alternative approach that leverages anchors.
To achieve smooth scrolling, utilize the scroll-behavior property (MDN reference) for the designated scrolling container:
<code class="css">scroll-behavior: smooth;</code>
This property is supported in modern browsers such as Firefox, Chrome, Safari, and Opera. However, note that browsers like Internet Explorer and non-Chromium Edge lack support for scroll-behavior.
Here's an example of how to implement this:
<code class="html"><head> <style type="text/css"> html { scroll-behavior: smooth; } </style> </head> <body id="body"> <a href="#foo">Go to foo!</a> <!-- Some content --> <div id="foo">That's foo.</div> <a href="#body">Back to top</a> </body></code>
Upon clicking the "Go to foo!" link, you'll experience a smooth scroll down to the "foo" element, and vice versa for the "Back to top" link.
This approach provides a convenient and smooth scrolling behavior without requiring additional buttons.
The above is the detailed content of How Can I Achieve Smooth Scrolling with CSS and Anchors?. For more information, please follow other related articles on the PHP Chinese website!