search
HomeBackend DevelopmentPHP TutorialCSS code to implement underline following sliding effect

This article mainly introduces you to pure CSS to realize the navigation bar underline following sliding effect. Friends who need it can refer to it. I hope it can help everyone.

The old rule is to post a picture first. How to use pure CSS to create the following effect?

You can take a moment before continuing to read the following. Try to think about the above effects or try it yourself to see if you can achieve the above effects cleverly without using JS.

OK, continue. This effect is a similar small problem I encountered in the process of business development. In fact, even if I use Javascript, my first reaction is that it feels very troublesome. So I've been wondering, is it possible to achieve this effect using only CSS?

Define requirements

We define simple rules, the requirements are as follows:

Assume that the HTML structure is as follows:


<ul>
  <li>不可思议的CSS</li>
  <li>导航栏</li>
  <li>光标小下划线跟随</li>
  <li>PURE CSS</li>
  <li>Nav Underline</li>
</ul>

The width of the li in the navigation column is not fixed

When moving from the left li of the navigation to the right li, the underline moves from left to right. In the same way, when moving from the right side of the navigation li to the left side li , the underline moves from right to left.

Implementation requirements

When I first saw this effect, I felt that this following animation was impossible to complete with CSS alone.

If you want to use only CSS to achieve it, you can only find another way and use some tricky methods.

Okay, let’s use some tricks to achieve this effect step by step using CSS. Analyze the difficulty:

The width is not fixed

The first difficulty is that the width of li is not fixed. Therefore, we may need to make a fuss about the width of li itself.

Since the width of each li is not necessarily the same, the length of its corresponding underscore must be adapted to it. Naturally, we will think of using its border-bottom.


li {
    border-bottom: 2px solid #000;
}

Then, it may look like this now (li are connected together, and the gaps between li are generated using padding):

Hidden by default, animation effect

Of course, there are no underlines here at the beginning, so we may need to hide them.


li {
    border-bottom: 0px solid #000;
}

Overturn and use pseudo elements

This doesn’t seem to work, because after hiding, when hovering li, underlining is needed Animation, and li itself must not be moved. Therefore, we consider using pseudo elements. Applies an underscore to each li pseudo-element.


li::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-bottom: 2px solid #000;
}

Let’s consider the animation of the first step. When hovering, the underline should move from one side to expand. Therefore, we use absolute positioning to set the width of the pseudo element of li to 0. When hovering, the width changes from width: 0 -> width: 100%. The CSS is as follows:


li::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 100%;
    border-bottom: 2px solid #000;
}
li:hover::before {
    width: 100%;
}

Obtained, the following effect:

Move left to left, move right to right

OK, feeling away Success is one step closer. Now there is one most difficult question left:

How to make the line follow the movement of the cursor, so that when moving from the left side of the navigation li to the right side li , the underline moves from left to right. In the same way, when moving from the right side of the navigation li to the left side li , the underline moves from right to left.

Let’s take a closer look, the current effect:

When switching from the first li to the second li, the first li is underlined The retrieval direction is incorrect. Therefore, maybe we need to shift the initial position of the underline and set it to left: 100%, so that every time the underline is retracted, the first li will be correct:


##

li::before {
    content: "";
    position: absolute;
    top: 0;
    left: 100%;
    width: 0;
    height: 100%;
    border-bottom: 2px solid #000;
}
li:hover::before {
    left: 0;
    width: 100%;
}

Look at the effect:

Well, carefully compare the two pictures. The second effect is actually picking up the sesame seeds and losing the watermelon. The direction of the first li is correct, but the moving direction of the underline of the second li is wrong again.

Magic~ Selector

So, we urgently need a method that can change the underline movement of the current hover's li without changing its next li The way the underline moves (good for tongue twisters).

Yes, here we can use the ~ selector to complete this difficult mission, which is also the most important part of this example.

对于当前 hover 的  li ,其对应伪元素的下划线的定位是  left: 100% ,而对于  li:hover ~ li::before ,它们的定位是  left: 0 。CSS 代码大致如下:


li::before {
    content: "";
    position: absolute;
    top: 0;
    left: 100%;
    width: 0;
    height: 100%;
    border-bottom: 2px solid #000;
    transition: 0.2s all linear;
}
li:hover::before {
    width: 100%;
    left: 0;
}
li:hover ~ li::before {
    left: 0;
}

至此,我们想要的效果就实现拉!撒花。看看:

 

效果不错,就是有点僵硬,我们可以适当改变缓动函数以及加上一个动画延迟,就可以实现上述开头里的那个效果了。当然,这些都是锦上添花的点缀。

完整的DEMO可以戳这里:  CodePen Demo -- 不可思议的CSS光标下划线跟随效果。

相关推荐:

jquery鼠标悬停导航下划线滑出实例分享

The above is the detailed content of CSS code to implement underline following sliding effect. 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 to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools