CSS Animation Example: Typewriter Effect
The "Typewriter Effect" is a nostalgic and highly engaging way to reveal a headline or key sentence, mimicking a person typing it out live.
This trick is entirely CSS-based! It relies on animating the width of the text container from 0 to 100%. Importantly, the text must be prevented from wrapping using white-space: nowrap and hidden when overflowing using overflow: hidden.
The magic ingredient is the steps() timing function. Instead of smoothly increasing the width, steps() chops the animation into discrete jumps. By setting the number of steps to roughly equal the number of characters in the string, it reveals one letter at a time.
We also run a secondary, infinite animation that toggles the border-color of the right border to simulate a blinking cursor.
Here is the code to create the Typewriter Effect.
Accessibility Considerations
Text that forces a user to wait to read it can be frustrating, especially for users with cognitive or reading disabilities, or those who rely on screen readers. Furthermore, the blinking cursor can be a distraction for users with ADHD or vestibular issues.
prefers-reduced-motion is a CSS media feature used to detect if a user has enabled a setting on their device to minimize the amount of non-essential animation or motion. We handle this by disabling both animations and ensuring the width is set to 100% so the string is immediately visible in its entirety.
Here's what we used in our example:
@media (prefers-reduced-motion: reduce) {
.typewriter-text {
/* Kill both the typing width change and cursor blink */
animation: none;
/* Ensure text is fully exposed */
width: 100%;
/* Hide the cursor line */
border-right: none;
}
}