简体   繁体   English

使用 :hover::after 从相对位置到绝对位置的平滑 CSS 过渡

[英]Smooth CSS transition from position relative to position absolute with :hover::after

I am trying to build an underline under the nav menu on hover.我正在尝试在悬停时在导航菜单下建立下划线。 I'm using the 'content' trick because I couldn't make what I wanted with just text decoration.我正在使用“内容”技巧,因为我无法仅通过文本装饰来制作我想要的东西。

I want something like this but with a smooth transition.我想要这样的东西,但过渡平稳。

Here's the CSS for it without transition because I couldn't make it work.这是没有过渡的CSS,因为我无法使其工作。

 div { display: flex; align-items: center; color: #ab9b8c; font-size: 20px; letter-spacing: 1.5px; text-decoration: none; height: 100%; cursor: pointer; transition: height 2s; position: relative; } div:hover::after { content: ''; position: absolute; bottom: -1px; width: 30px; height: 3px; border-radius: 200px; border: 1px solid #9f9182; }
 <div>test <div/>

As Paulie_D mentioned, you can't do transitions on position attributes.正如 Paulie_D 提到的,您不能对position属性进行转换。 See: https://www.w3schools.com/cssref/pr_class_position.asp "Animatable: no."请参阅: https ://www.w3schools.com/cssref/pr_class_position.asp“动画:否。”

Several other attributes are fair game though.不过,其他几个属性是公平的游戏。 Here's one using the width and the border:这是使用宽度和边框的一个:

 div { display: flex; align-items: center; color: #ab9b8c; font-size: 20px; letter-spacing: 1.5px; text-decoration: none; height: 100%; cursor: pointer; transition: height 2s; position: relative; } div::after { content: ''; position: absolute; bottom: -1px; width: 0px; height: 3px; border-radius: 200px; border: 0px solid #9f9182; transition: all 0.2s linear; } div:hover::after { width: 30px; border: 1px solid #9f9182; transition: all 0.2s linear; }
 <div>test </div>

Here's an opacity:这是一个不透明度:

 div { display: flex; align-items: center; color: #ab9b8c; font-size: 20px; letter-spacing: 1.5px; text-decoration: none; height: 100%; cursor: pointer; transition: height 2s; position: relative; } div::after { content: ''; position: absolute; bottom: -1px; width: 30px; height: 3px; border-radius: 200px; border: 1px solid #9f9182; opacity: 0; transition: all 0.2s linear; } div:hover::after { opacity: 1; transition: all 0.2s linear; }
 <div>test </div>

Here's both at once because why not:这两者同时出现,因为为什么不:

 div { display: flex; align-items: center; color: #ab9b8c; font-size: 20px; letter-spacing: 1.5px; text-decoration: none; height: 100%; cursor: pointer; transition: height 2s; position: relative; } div::after { content: ''; position: absolute; bottom: -1px; width: 0px; height: 3px; border-radius: 200px; border: 0px solid #9f9182; opacity: 0; transition: all 0.2s linear; } div:hover::after { width: 30px; opacity: 1; border: 1px solid #9f9182; transition: all 0.2s linear; }
 <div>test </div>

So on and so on等等等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM