Animating Link Underlines

Hover this text

I recently added a simple visual effect to this blog that I quickly fell in love with: when you hover blog headers, the link’s underline is revealed by animating it out from the center. You can try it in the banner above. Creating this effect is surprisingly easy, doesn’t require any additional DOM elements to be added through HTML, and falls back nicely for browsers that don’t support CSS animations (it will just show up as a regular underline).

The first thing we need to do is turn off text-decoration, and set the link’s position to relative. For simplicitiy’s sake, we’ll also make sure the link doesn’t change color on hover. Here we’re applying the effect to all link elements inside h2s:

h2 > a {
  position: relative;
  color: #000;
  text-decoration: none;

h2 > a:hover {
  color: #000;

Next, we want to add the border, and hide it through a transformation. We do this by inserting it with :before, and setting its X scale to 0. As a fallback, we hide it with visibility: hidden for browsers that don’t support CSS animations.

h2 > a:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: #000;
  visibility: hidden;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transition: all 0.3s ease-in-out 0s;
  transition: all 0.3s ease-in-out 0s;

At the very bottom we tell the element to animate all changes applied to it, with a duration of 0.3 seconds. For the animation to appear, now we just need to make the element visible again on hover, and set its X scale back to 1:

h2 > a:hover:before {
  visibility: visible;
  -webkit-transform: scaleX(1);
  transform: scaleX(1);

And that’s it! Firefox has had support for animation and transform without the moz prefix since version 16.0 (for over a year), so I’ve left out the prefix in the code. If you want to be safe, you should add -o and -moz to all animations and transforms.