The Secret to Animated CSS Underlines
For decades, the standard way to underline a link was using text-decoration: underline; or a basic border-bottom. While functional, these properties are incredibly rigid and impossible to animate smoothly.
Modern web designers use a clever hack involving the CSS background-image property to create thick marker highlights, sweeping hover effects, and animated underlines that are completely hardware-accelerated.
How the Background Gradient Hack Works
Instead of drawing a border, we draw a flat “image” behind the text using linear-gradient() with the exact same solid color. Because it is treated as a background image, we gain access to two magical properties: background-size and background-position.
- Controlling Thickness: By setting the
background-size to something like 100% 40%, the background will span the full width of the text but only cover the bottom 40% of the height, creating a “Marker Pen” effect. Changing it to 100% 2px creates a standard thin underline. - Animating the Sweep: To make the highlight “grow” when a user hovers over it, we start with a
background-size of 0% 40% (making it invisible). On :hover, we transition it to 100% 40%. - Controlling Direction: By changing the
background-position, we dictate where the animation originates. left bottom makes it sweep from the left. center bottom makes it grow outward from the middle!
Accessibility Tip: If you are using this effect on links inside a paragraph of text, ensure your Highlight Color has enough contrast against the background so users immediately recognize it as a clickable element, even before hovering.