search
HomeWeb Front-endCSS TutorialHow to implement a smooth scrolling navigation menu on a web page through pure CSS

How to implement a smooth scrolling navigation menu on a web page through pure CSS

How to implement a smooth scrolling navigation menu on a web page through pure CSS

Guiding users to navigate in a web page is an important design element, and the smooth scrolling navigation menu is provided A way to create a user-friendly navigation experience. This article will introduce how to implement such a navigation menu through pure CSS and provide corresponding code examples.

1. HTML structure

First, we need to create the basic structure of the navigation menu in HTML. Here is a simple example:

<nav class="smooth-scroll-nav">
  <ul class="smooth-scroll-menu">
    <li><a href="#section1">Section 1</a></li>
    <li><a href="#section2">Section 2</a></li>
    <li><a href="#section3">Section 3</a></li>
    <li><a href="#section4">Section 4</a></li>
  </ul>
</nav>

<section id="section1">
  <h2 id="Section">Section 1</h2>
  <p>This is the content of section 1.</p>
</section>

<section id="section2">
  <h2 id="Section">Section 2</h2>
  <p>This is the content of section 2.</p>
</section>

<section id="section3">
  <h2 id="Section">Section 3</h2>
  <p>This is the content of section 3.</p>
</section>

<section id="section4">
  <h2 id="Section">Section 4</h2>
  <p>This is the content of section 4.</p>
</section>

In the above example, we created a <nav></nav> element as a container for the navigation menu and then added a inside it. The <ul></ul> element serves as a list of menus, with corresponding menu items added. Next, we use the <section></section> element to create the content for each section, where the id attribute corresponds to the href attribute in the menu item.

2. CSS Style

Next, we will use CSS to create a smooth scrolling effect. First, we need to apply some basic styles on the navigation menu:

.smooth-scroll-nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #333;
  padding: 10px 0;
}

.smooth-scroll-menu {
  list-style: none;
  margin: 0;
  padding: 0;
  text-align: center;
}

.smooth-scroll-menu li {
  display: inline-block;
  margin-right: 15px;
}

.smooth-scroll-menu li:last-child {
  margin-right: 0;
}

.smooth-scroll-menu a {
  color: #fff;
  text-decoration: none;
  padding: 5px 10px;
}

.smooth-scroll-menu a:hover {
  background-color: #fff;
  color: #333;
}

In the above code, we added the position: fixed; attribute to the navigation menu container to make it fixed. top of the page. Then, set the corresponding background color, padding, font color and other styles. Next, we use the inline-block layout to display the menu items horizontally and add some spacing and hover effects.

Next, we will add a smooth scrolling effect. We will use the scroll-behavior property of CSS to achieve this effect. In some cases, browsers may not support this attribute, so we also need to provide a fallback solution for browsers that do not support it.

html {
  scroll-behavior: smooth;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  /* 回退方案:使用jQuery滚动动画 */
  .smooth-scroll-nav a {
    transition: all 0.3s ease-in-out;
  }
  
  .smooth-scroll-nav a[href^="#"] {
    position: relative;
  }
  
  .smooth-scroll-nav a[href^="#"]:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 0;
    height: 2px;
    background-color: #fff;
    transition: all 0.3s ease-in-out;
    transform: translateX(-50%);
  }
  
  .smooth-scroll-nav a[href^="#"]:hover:after,
  .smooth-scroll-nav a[href^="#"]:focus:after {
    width: 100%;
  }
}

In the above code, we first use scroll-behavior: smooth; to apply the smooth scrolling effect. We then use the @media query to provide a fallback for browsers that do not support the scroll-behavior attribute.

In the fallback solution, we add a transition effect to the menu item so that it has an underline effect when the mouse is hovered. We use the ::after pseudo-element to create this underline and use a transition effect to animate it. Through the corresponding transition attributes, we realize the expansion and contraction of the underline.

3. JavaScript additional functions

If you want to achieve smooth scrolling in browsers that do not support the scroll-behavior attribute, we can also use JavaScript to achieve it. The following is a sample code using the jQuery library:

$(function() {
  $('a[href^="#"]').on('click', function(e) {
    e.preventDefault();
    var target = $(this.getAttribute('href'));
    if (target.length) {
      $('html, body').stop().animate({
        scrollTop: target.offset().top
      }, 1000);
    }
  });
});

In the above code, we use jQuery’s animate function to achieve a smooth scrolling effect. When a menu item is clicked, we first prevent the default jump behavior, then use the offset() function to obtain the position of the target element, and implement the page scrolling through the animate function .

This completes the implementation of a smooth scrolling navigation menu based on pure CSS. Using this method, we can provide a smooth navigation experience for the web page and control the appearance and behavior of the entire menu through CSS styles.

The above is the detailed content of How to implement a smooth scrolling navigation menu on a web page through pure CSS. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How We Tagged Google Fonts and Created goofonts.comHow We Tagged Google Fonts and Created goofonts.comApr 12, 2025 pm 12:02 PM

GooFonts is a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been tagging Google

Timeless Web Dev ArticlesTimeless Web Dev ArticlesApr 12, 2025 am 11:44 AM

Pavithra Kodmad asked people for recommendations on what they thought were some of the most timeless articles about web development that have changed their

The Deal with the Section ElementThe Deal with the Section ElementApr 12, 2025 am 11:39 AM

Two articles published the exact same day:

Practice GraphQL Queries With the State of JavaScript APIPractice GraphQL Queries With the State of JavaScript APIApr 12, 2025 am 11:33 AM

Learning how to build GraphQL APIs can be quite challenging. But you can learn how to use GraphQL APIs in 10 minutes! And it so happens I've got the perfect

Component-Level CMSsComponent-Level CMSsApr 12, 2025 am 11:09 AM

When a component lives in an environment where the data queries populating it live nearby, there is a pretty direct line between the visual component and the

Set Type on a Circle... with offset-pathSet Type on a Circle... with offset-pathApr 12, 2025 am 11:00 AM

Here's some legit CSS trickery from yuanchuan. There is this CSS property offset-path. Once upon a time, it was called motion-path and then it was renamed. I

What does 'revert' do in CSS?What does 'revert' do in CSS?Apr 12, 2025 am 10:59 AM

Miriam Suzanne explains in a Mozilla Developer video on the subject.

The Modern LoversThe Modern LoversApr 12, 2025 am 10:58 AM

I love stuff like this.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment