Animated Navigation Link Underline with CSS Transition
Build an animated underline effect for navigation links using CSS transition and pseudo-elements. Includes expand-from-center and slide-in variants.
Detailed Explanation
Animated Link Underline
An animated underline that grows on hover is a polished alternative to the default text-decoration: underline. It uses a pseudo-element with a width transition.
Expand from Center
.nav-link {
position: relative;
text-decoration: none;
}
.nav-link::after {
content: "";
position: absolute;
bottom: -2px;
left: 50%;
width: 0;
height: 2px;
background-color: currentColor;
transition: width 0.3s ease-out, left 0.3s ease-out;
}
.nav-link:hover::after {
width: 100%;
left: 0;
}
Slide from Left
.nav-link::after {
content: "";
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background-color: currentColor;
transition: width 0.3s ease-out;
}
.nav-link:hover::after {
width: 100%;
}
Using Transform for Better Performance
For GPU-accelerated performance, use transform: scaleX() instead of width:
.nav-link::after {
content: "";
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 2px;
background-color: currentColor;
transform: scaleX(0);
transform-origin: right;
transition: transform 0.3s ease-out;
}
.nav-link:hover::after {
transform: scaleX(1);
transform-origin: left;
}
This scaleX approach is more performant because it avoids animating the width property (which triggers layout). The pseudo-element starts at full width but is visually collapsed via scaleX(0), then expands on hover.
Use Case
Animated underlines are used in website headers, navigation bars, sidebar menus, breadcrumbs, and tab components to provide elegant hover feedback without relying on browser-default text decoration.