ホーム > Other > How to Implement Smooth Scroll with Page Anchors 【Without jQuery】
Other

How to Implement Smooth Scroll with Page Anchors 【Without jQuery】

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents for other articles

⇨ Click here for the table of contents for WordPress articles

Implement smooth scroll with page anchors. You can now easily implement it with just CSS without jQuery.

This is an article aimed at HTML and CSS beginners.

What is a page anchor?

It refers to the functionality of scrolling to a specific location on the same page.

Pages that are long vertically, where clicking on a menu item will take you to the corresponding section, are very user-friendly.

On my blog as well, clicking on the table of contents implements page anchors in the same way.

Implementation of page anchors

It is possible to implement it just by giving an id to the element you want to scroll to and the href attribute of the a tag.

<a href="#first">Go to 1</a>
<a href="#second">Go to 2</a>
<a href="#third">Go to 3</a>
<a href="#forth">Go to 4</a>
<a href="#fifth">Go to 5</a>

<div style="margin: 1000px;" id="first">1</div>
<div style="margin: 1000px;" id="second">2</div>
<div style="margin: 1000px;" id="third">3</div>
<div style="margin: 1000px;" id="forth">4</div>
<div style="margin: 1000px;" id="fifth">5</div>

In this way, by specifying an id for the destination you want to scroll to, and specifying that id in the href attribute of the a tag, implementation is possible.

<!-- Specify to scroll to the area with id="first" -->
<a href="#first">Go to 1</a>

<!-- Specify the id as "first" -->
<div style="margin: 1000px;" id="first">1</div>

That's the basic way to write it.

Implementing Smooth Scroll

Smooth scroll refers to gradually scrolling the page anchor we implemented earlier with a "smooth" scrolling effect.

Implementation

Just add one line in CSS.

html {
  scroll-behavior: smooth;
}

That's it.

I don't know when this CSS property was implemented, but it no longer requires jQuery.

Done!

Reference (External Site)

Summary

I have written about how to easily implement smooth scroll. I hope it can be helpful to someone.

If you have any questions or find any mistakes, please contact me via Twitter DM!

That's all!

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!