Emmanuel Akinfulubi

HTML and CSSPractical I

Animated underline on hover in CSS

8 An animated underline on hover

fair

Make a link grow an underline from nothing when hovered, animating rather than snapping. Respect a reader who has asked for less motion.

Stuck? Three hints, smallest first
  1. 1. Use a pseudo-element with transform: scaleX(0), then scale it to 1 on hover.
  2. 2. Animating transform is smooth; animating width makes the browser re-lay-out every frame.
  3. 3. @media (prefers-reduced-motion: reduce) is how you honour the system setting.

index.html

<p>Hover the <a class="grow" href="#">underlined link</a> to see it animate.</p>

style.css

.grow {
  position: relative;
  display: inline-block;   /* so the underline spans the text, not the line */
  color: #3055d8;
  text-decoration: none;
}

.grow::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 100%;
  height: 2px;
  background: currentColor;
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 200ms ease;
}

.grow:hover::after,
.grow:focus-visible::after {
  transform: scaleX(1);
}

/* Someone who has asked for less motion gets the underline without the slide. */
@media (prefers-reduced-motion: reduce) {
  .grow::after { transition: none; }
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
9 checks that prove this answer

Assertions, run in the browser. The markup and styles above are handed to them as html and css, so press Run and each check prints ok. The build fails if a single one fails.

Checks for exercise 8

test('a pseudo-element draws the underline', /::after/.test(css), true);
test('it starts scaled to nothing', /scaleX\(0\)/.test(css), true);
test('and grows to full width on hover', /scaleX\(1\)/.test(css), true);
test('transform is what animates, not width', /transition\s*:\s*transform/.test(css), true);
test('it grows from the left', declares(css, 'transform-origin', 'left'), true);
test('inline-block keeps it to the text width', declares(css, 'display', 'inline-block'), true);
test('keyboard focus gets the same effect', /focus-visible/.test(css), true);
test('reduced motion is respected', /prefers-reduced-motion/.test(css), true);
test('the underline inherits the link colour', /currentColor/i.test(css), true);

Output


      

Three things here are habits rather than tricks. Animating transform instead of width keeps the work on the compositor, so it stays smooth; animating width forces a re-layout every frame. Adding :focus-visible alongside :hover means keyboard users get the same feedback, which a hover-only rule silently denies them. And prefers-reduced-motion is a real accessibility setting people turn on because motion makes them ill — honouring it costs three lines.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.