R M R M - 1 month ago 16
CSS Question

CSS3 underline from left to right

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: #fff;
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?

Answer

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%;
}

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

Comments