悬停时从左到右下划线

Underline from left to right on hover in and out

通过下面的代码,我得到了从左到右的悬停下划线效果。

.underline {
  display: inline;
  position: relative;
  overflow: hidden;
}
.underline:after {
  content: "";
  position: absolute;
  z-index: -1;
  left: 0;
  right: 100%;
  bottom: -5px;
  background: #000;
  height: 4px;
  transition-property: left right;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}
.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  right: 0;
}
<p>hello, link is <a href="#" class="underline">underline</a>
</p>

当您不悬停时,左侧的 :after 元素 returns 为初始状态。有什么方法可以让 :after 在您离开悬停时向右 而不是向左?

您可以尝试为宽度而不是 right/left 属性设置动画。

.underline {
  display: inline;
  position: relative;
  overflow: hidden;
}
.underline:after {
  content: "";
  position: absolute;
  z-index: -1;
  right: 0;
  width: 0;
  bottom: -5px;
  background: #000;
  height: 4px;
  transition-property: width;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}
.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  left: 0;
  right: auto;
  width: 100%;
}
<p>hello, link is <a href="#" class="underline">underline</a></p>

请参阅此 fiddle 以获取工作示例:https://jsfiddle.net/1gyksyoa/

基于此答案: 您可以更改悬停时的 transform-origin 属性 以实现 "hover out" 您正在寻找的效果。这是一个例子:

.expand{
  position:relative;
  text-decoration:none;
  display:inline-block;
}
.expand:after {
  display:block;
  content: '';
  border-bottom: solid 3px #000;  
  transform: scaleX(0);  
  transition: transform 250ms ease-in-out;
  transform-origin:100% 50%
}
.expand:hover:after { 
  transform: scaleX(1);
  transform-origin:0 50%;
}
Here is some dummy text <a href="#" class="expand">expand</a>