Home > Web Front-end > CSS Tutorial > How Can I Achieve Smooth Scrolling with CSS and Anchors?

How Can I Achieve Smooth Scrolling with CSS and Anchors?

Barbara Streisand
Release: 2024-10-29 18:24:02
Original
272 people have browsed it

How Can I Achieve Smooth Scrolling with CSS and Anchors?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template