15

With the following code I get an hover underline effect from left to right.

.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>

When you're not in hover, the :after element returns to the left, the initial state. Is there any way that the :after goes to the right and not to the left when you leave the hover?

web-tiki
  • 99,765
  • 32
  • 217
  • 249
R M
  • 297
  • 1
  • 3
  • 14
  • You can add a class to your anchor tag with jQuery [hover](https://api.jquery.com/hover/) function and put some styling in the class you defined in the jQuery script. – Babidi Oct 25 '16 at 14:21
  • 1
    Are you by any chance looking for something similar to this - http://stackoverflow.com/questions/28623446/expand-bottom-border-on-hover? – Harry Oct 25 '16 at 14:22

2 Answers2

28

You can try animating the width instead of the right/left properties.

.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>

See this fiddle for a working example: https://jsfiddle.net/1gyksyoa/

Oriol
  • 274,082
  • 63
  • 437
  • 513
Vlad Cazacu
  • 1,520
  • 12
  • 12
  • Well, done, but I would add `pointer-events: none`. Otherwise it can go crazy in the race condition that you first hover the link, unhover it, but before the underline disappears you hover the right part of the underline. Then the underline will be moved to the left and thus be no longer hovered, so it will be moved to the right and become hovered again, and so on. – Oriol Oct 25 '16 at 15:11
14

Based on this answer : Expand bottom border on hover you can change the transform-origin property on hover to achieve the "hover out" effect you are looking for. Here is an example :

.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>
Community
  • 1
  • 1
web-tiki
  • 99,765
  • 32
  • 217
  • 249