Text Underline Animation using Tailwind CSS

Jun 30, 20231 min read

Demo: Hover me!

Add this to your css and use hover-underline-animation to text that you want to underline on hover.

We create this class in globals.css file so we can reuse it later we need it. Optionally, we can also create HoverUnderlineText component.

Steps:

  1. We need to target the ::before selector to create the underline effect and when it is hovered, we will show the underline.
  2. To do that, we create an underline that is initially scaled by 0 in horizontal axis. We do this by adding h-[2px] w-full and position it to be under the text using absolute bottom-0 left-0.
  3. When it is hovered, we scale the X axis by 100% so it is shown.
  4. To make the animation start from left to right, we add origin-left. If we want the animation to start from center, omit this class.

Voila, we now have underline text animation!

.hover-underline-animation {
  @apply inline-block relative;
}

.hover-underline-animation::after {
  @apply dark:bg-white bg-black content-[''] absolute w-full scale-x-0 h-[2px] bottom-0 left-0 origin-left transition-all ease-in-out;
}

.hover-underline-animation:hover::after {
  @apply scale-x-100;
}