EdwardBlack EdwardBlack - 1 month ago 9
HTML Question

How to let underline fade in beneath link on hover?

How can I fade in an underline on hover over a link like in the video below?

GIF

I found this CSS by using the developer console, but I can't figure out how it works.

.mainContent p>a:hover::after, .mainContent li>a:hover::after, .mainContent .text a:hover::after, .mainContent p>a:focus::after, .mainContent li>a:focus::after, .mainContent .text a:focus::after {
opacity: 1;
-webkit-transform: translateY(-2px);
-moz-transform: translateY(-2px);
transform: translateY(-2px);
}
.mainContent p>a::after, .mainContent li>a::after, .mainContent .text a::after {
position: absolute;
top: 100%;
left: 0;
width: 100%;
height: 1px;
background: rgba(226,0,26,1);
content: '';
opacity: 0;
-webkit-transition: opacity 0.15s,-webkit-transform 0.2s;
-moz-transition: opacity 0.15s,-moz-transform 0.2s;
transition: opacity 0.15s,transform 0.2s;
-webkit-transform: translateY(4px);
-moz-transform: translateY(4px);
transform: translateY(4px);
}


HTML

<a href="http://www.google.de" target="_blank">Hallenplan</a>


How does this work and is there a even better way?

Answer

To do this effect you need two things:

  • Give the a a position attribute
  • Animate its after element by placing it at the bottom through position: absolute and then transforming it.

One possible way is:

a {
  position: relative;
  text-decoration: none;
}

a:hover::after, a:focus::after {
  opacity: 1;
  transform: translateY(-2px);
}

a::after {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  height: 1px;
  background: black;
  content: '';
  opacity: 0;
  transition: opacity 0.2s, transform 0.2s;
  transform: translateY(4px);
}
<a href="http://www.stackoverflow.com">
    StackOverflow
</a>