Tip 35/72

How to create in-out animated underline

Learn how to create an in-out animated underline.

Animating an underline on hover is a great way to enhance the user interface. This effect uses Tailwind CSS’s before pseudo-element and transition utilities for smooth animation. Here’s how to achieve it:

Start with a basic <a> tag and wrap it in a container.

<a href="#" class="block relative py-2 text-gray-700 duration-300 hover:text-gray-950">Hover me</a>

Key Classes:

  • block: Makes the link a block element for easier positioning.
  • relative: Establishes a positioning context for the before pseudo-element.

Step 2: Add the before Pseudo-Element

Use Tailwind’s before: variant to create the animated underline.

<a 
    href="#" 
    class="block w-fit relative py-0.5 text-sm text-gray-700 duration-300 hover:text-gray-950 before:absolute before:bottom-0 before:inset-x-0 before:h-px before:rounded-full before:bg-primary-600 before:origin-right before:scale-x-0 before:transition-transform before:duration-300 before:ease-in-out hover:before:origin-left hover:before:scale-x-100"
>
    Hover me
</a>

Key Additions:

Underline setup:

  • before:absolute: Positions the underline relative to the link.
  • before:bottom-0 before:inset-x-0: Aligns the underline at the bottom of the link and spans it horizontally.
  • before:h-px: Sets the height of the underline to 1px.
  • before:rounded-full: Gives the underline rounded edges.
  • before:bg-primary-600: Specifies the underline color.

Animation setup:

  • before:origin-right: Sets the transform origin to the right, making the underline shrink and expand from the right initially.
  • before:scale-x-0: Shrinks the underline to zero width by default.
  • before:transition-transform: Applies a smooth transformation animation.
  • before:duration-300 and before:ease-in-out: Define the animation speed and easing for a smooth effect.

Hover effect:

  • hover:before:origin-left: Changes the transform origin to the left on hover.
  • hover:before:scale-x-100: Expands the underline fully on hover.

Final Notes

  • Use duration-300 to control the speed of the animation; adjust as needed for faster or slower effects.
  • ease-in-out provides a smooth animation. Experiment with other easing options for different effects.
  • Replace bg-primary-600 with a custom class or color to match your design.

This method creates a polished, interactive link with minimal effort, perfect for modern web designs!