先上张图,如何使用纯 CSS 制作如下效果?
在继续阅读下文之前,你可以先缓一缓。尝试思考一下上面的效果或者动手尝试一下,不借助 JS ,能否巧妙的实现上述效果。
OK,继续。这个效果是我在业务开发的过程中遇到的一个类似的小问题。其实即便让我借助 Javascript ,我的第一反应也是,感觉很麻烦啊。所以我一直在想,有没有可能只使用 CSS 完成这个效果呢?
定义需求
我们定义一下简单的规则,要求如下:
- 假设 HTML 结构如下:
<ul>
<li>不可思议的CSS</li>
<li>导航栏</li>
<li>光标小下划线跟随</li>
<li>PURE CSS</li>
<li>Nav Underline</li>
</ul>
- 导航栏目的
li
的宽度是不固定的 - 当从导航的左侧
li
移向右侧li
,下划线从左往右移动。同理,当从导航的右侧li
移向左侧li
,下划线从右往左移动。
实现需求
第一眼看到这个效果,感觉这个跟随动画,仅靠 CSS 是不可能完成的。
如果想只用 CSS 实现,只能另辟蹊径,使用一些讨巧的方法。
好,下面就借助一些奇技淫巧,使用 CSS 一步一步完成这个效果。分析一下难点:
宽度不固定
第一个难点, li
的宽度是不固定的。所以,我们可能需要从 li
本身的宽度上做文章。
既然每个 li
的宽度不一定,那么它对应的下划线的长度,肯定是是要和他本身相适应的。自然而然,我们就会想到使用它的 border-bottom
。
li {
border-bottom: 2px solid #000;
}
那么,可能现在是这样子的(li 之间是相连在一起的,li 间的间隙使用 padding
产生):
默认隐藏,动画效果
当然,这里一开始都是没有下划线的,所以我们可能需要把他们给隐藏起来。
li {
border-bottom: 0px solid #000;
}
推翻重来,借助伪元素
这样好像不行,因为隐藏之后,hover li
的时候,需要下划线动画,而 li
本身肯定是不能移动的。所以,我们考虑借助伪元素。将下划线作用到每个 li
的伪元素之上。
li::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-bottom: 2px solid #000;
}
下面考虑第一步的动画,hover 的时候,下划线要从一侧运动展开。所以,我们利用绝对定位,将 li
的伪元素的宽度设置为0,在 hover 的时候,宽度从 width: 0 -> width: 100%
,CSS 如下:
li::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
border-bottom: 2px solid #000;
}
li:hover::before {
width: 100%;
}
得到,如下效果:
左移左出,右移右出
OK,感觉离成功近了一步。现在还剩下一个最难的问题:
如何让线条跟随光标的移动动作,实现当从导航的左侧 li
移向右侧 li
,下划线从左往右移动。同理,当从导航的右侧 li
移向左侧 li
,下划线从右往左移动。
我们仔细看看,现在的效果:
当从第一个 li
切换到第二个 li
的时候,第一个 li
下划线收回的方向不正确。所以,可以能我们需要将下划线的初始位置位移一下,设置为 left: 100%
,这样每次下划线收回的时候,第一个 li
就正确了:
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%;
}
额,仔细对比两张图,第二种效果其实是捡了芝麻丢了西瓜。第一个 li
的方向是正确了,但是第二个 li
下划线的移动方向又错误了。
神奇的 ~ 选择符
所以,我们迫切需要一种方法,能够不改变当前 hover 的 li
的下划线移动方式却能改变它下一个 li
的下划线的移动方式(好绕口)。
没错了,这里我们可以借助 ~
选择符,完成这个艰难的使命,也是这个例子中,最最重要的一环。
对于当前 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
最后
本方法最大的瑕疵在于一开始进入第一个 li 的时候,线条只能是从右往左,除此之外,都能很好的实现跟随效。
Hey There. I discovered your weblog using msn. This is an extremely neatly written article. I will be sure to bookmark it and come back to read more of your helpful info. Thank you for the post. I will certainly return.
Can I just say what a relief to find someone who actually is aware of what theyre speaking about on the internet. You positively know find out how to deliver a difficulty to gentle and make it important. Extra folks have to read this and understand this facet of the story. I cant consider youre not more popular because you undoubtedly have the gift.
Thanks for this excellent article. Also a thing is that almost all digital cameras are available equipped with any zoom lens that permits more or less of a scene for being included by way of ‘zooming’ in and out. These kind of changes in {focus|focusing|concentration|target|the a**** length will be reflected in the viewfinder and on large display screen right at the back of the very camera.
Pretty portion of content. I just stumbled upon your weblog and in accession capital to say that I acquire actually enjoyed account your blog posts. Anyway I will be subscribing to your augment and even I fulfillment you access persistently fast.
There are some attention-grabbing points in time on this article however I don?t know if I see all of them center to heart. There’s some validity however I will take hold opinion until I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as properly
Your writing is insightful and thought-provoking, I always come away with new ideas.
WONDERFUL Post.thanks for share..extra wait .. ?
I was impressed with the wide selection of MAN trucks available at amcauto.co. They had something to suit every need and budget.
I have observed that over the course of developing a relationship with real estate proprietors, you’ll be able to come to understand that, in most real estate contract, a payment is paid. In the long run, FSBO sellers never “save” the payment. Rather, they struggle to earn the commission by means of doing the agent’s occupation. In completing this task, they expend their money and also time to carry out, as best they’re able to, the tasks of an broker. Those tasks include displaying the home by means of marketing, showing the home to prospective buyers, building a sense of buyer desperation in order to make prompt an offer, booking home inspections, handling qualification investigations with the loan company, supervising repairs, and assisting the closing of the deal.
I have been absent for a while, but now I remember why I used to love this blog. Thanks , I?ll try and check back more often. How frequently you update your web site?
The very root of your writing whilst sounding reasonable at first, did not really work well with me after some time. Someplace within the paragraphs you actually managed to make me a believer unfortunately just for a short while. I nevertheless have got a problem with your jumps in assumptions and you might do nicely to fill in all those gaps. When you actually can accomplish that, I will definitely end up being impressed.
“I’ve been following your blog for a while now and I have to say, I’m continually impressed by the quality of your writing and the depth of your knowledge. Keep up the great work!”
How can I contact you? I am interested in more information.
I?d must check with you here. Which is not something I usually do! I take pleasure in studying a post that can make people think. Additionally, thanks for permitting me to comment!
you’re actually a good webmaster. The web site loading velocity is amazing. It seems that you are doing any distinctive trick. In addition, The contents are masterpiece. you have performed a fantastic job on this subject!
Attractive section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access consistently rapidly.
I used to be recommended this website through my cousin. I’m no longer certain whether or not this put up is written through him as nobody else know such distinct about my trouble. You’re incredible! Thank you!
This is the suitable blog for anybody who desires to find out about this topic. You understand so much its virtually onerous to argue with you (not that I truly would want?HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Great stuff, simply nice!
Fantastic goods from you, man. I’ve understand your stuff previous to and you are just extremely magnificent. I really like what you have acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still care for to keep it wise. I can’t wait to read far more from you. This is really a tremendous web site.
I like the helpful information you provide in your articles. I will bookmark your weblog and check again here regularly. I’m quite sure I will learn lots of new stuff right here! Best of luck for the next!
A lot of whatever you articulate is astonishingly legitimate and it makes me ponder why I had not looked at this with this light before. This article really did turn the light on for me as far as this particular topic goes. But at this time there is just one point I am not too comfortable with so while I make an effort to reconcile that with the actual core idea of the issue, let me see what all the rest of your subscribers have to say.Well done.
I was suggested this website by way of my cousin. I am no longer sure whether this post is written by him as no one else recognise such targeted about my difficulty. You are wonderful! Thank you!
F*ckin? amazing issues here. I?m very satisfied to look your post. Thank you so much and i am looking ahead to touch you. Will you please drop me a mail?
Very nice post. I just stumbled upon your weblog and wanted to say that I’ve really enjoyed surfing around your blog posts. After all I will be subscribing to your feed and I hope you write again soon!
One other issue is when you are in a predicament where you will not have a co-signer then you may really want to try to make use of all of your school funding options. You could find many awards and other scholarships or grants that will offer you funding to help you with institution expenses. Thanks alot : ) for the post.
Thanks a lot for the helpful posting. It is also my opinion that mesothelioma cancer has an really long latency time period, which means that warning signs of the disease might not emerge until 30 to 50 years after the primary exposure to mesothelioma. Pleural mesothelioma, that’s the most common style and influences the area about the lungs, may cause shortness of breath, chest pains, including a persistent coughing, which may result in coughing up bloodstream.
It?s really a great and useful piece of information. I am satisfied that you shared this useful information with us. Please keep us informed like this. Thank you for sharing.
Great ? I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your client to communicate. Excellent task..
Simply desire to say your article is as surprising. The clearness to your put up is simply great and i could suppose you are a professional in this subject. Well with your permission let me to grasp your RSS feed to keep up to date with imminent post. Thanks a million and please carry on the rewarding work.