


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!

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

Dreamweaver CS6
Visual web development tools
