Hovering clears the line and types it back one character at a time behind a moving caret, which keeps blinking at the end. steps() on clip-path and on the caret keep both in sync.
Also known as: typewriter effect on hover, retype text animation, typing hover effect.
<div class="hfx-text-typewriter"><span>Hello, world</span></div>
.hfx-text-typewriter {
--c: var(--hfx-color, #3b82f6);
font-size: calc(var(--hfx-size, 16px) * 2);
font-family: system-ui, sans-serif;
font-weight: 800;
line-height: 1.15;
cursor: default;
position: relative;
display: inline-block;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-weight: 700;
white-space: nowrap;}
.hfx-text-typewriter span { display: inline-block; }
.hfx-text-typewriter::after {
content: "";
position: absolute;
top: 0.12em;
bottom: 0.12em;
left: 0;
width: 0.5ch;
background: var(--c);
/* 12 = number of characters */
transform: translateX(12.2ch);
}
.hfx-text-typewriter:hover span { animation: hfx-text-typewriter-type 1.2s steps(12) both; }
.hfx-text-typewriter:hover::after {
animation: hfx-text-typewriter-caret 1.2s steps(12) both,
hfx-text-typewriter-blink 0.8s step-end 1.2s infinite;
}
@keyframes hfx-text-typewriter-type {
from { clip-path: inset(0 100% 0 0); }
to { clip-path: inset(0); }
}
@keyframes hfx-text-typewriter-caret {
from { transform: translateX(0); }
to { transform: translateX(12.2ch); }
}
@keyframes hfx-text-typewriter-blink {
50% { opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
.hfx-text-typewriter, .hfx-text-typewriter *, .hfx-text-typewriter::before, .hfx-text-typewriter::after, .hfx-text-typewriter *::before, .hfx-text-typewriter *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}--hfx-color on the element or a parent.
Currently previewing #3b82f6.--hfx-size. Every other dimension is in
em, so the whole thing scales together. Currently previewing 16px.transition or animation
shorthand. Staggered delays are relative, so they keep their rhythm.