How to Create Typing Animation with CSS | Simple Guide
Create a typing animation in CSS by using
@keyframes to change the width of a text container from 0 to full width and apply overflow: hidden with white-space: nowrap. Use the steps() timing function to simulate typing letter by letter.Syntax
The typing animation uses the @keyframes rule to animate the width property of a text container. The container must have overflow: hidden and white-space: nowrap to hide the overflowing text and keep it on one line. The animation uses steps(n) to jump in discrete steps, where n is the number of characters.
css
@keyframes typing {
from { width: 0; }
to { width: 100%; }
}
.typing {
overflow: hidden;
white-space: nowrap;
border-right: 0.15em solid black; /* cursor effect */
animation: typing 3s steps(30) forwards;
}Example
This example shows a simple typing animation on a single line of text. The text appears letter by letter with a blinking cursor effect.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Typing Animation Example</title> <style> .typing { font-family: monospace; font-size: 1.5rem; white-space: nowrap; overflow: hidden; border-right: 0.15em solid black; width: 0; animation: typing 4s steps(20) forwards, blink-caret 0.75s step-end infinite; } @keyframes typing { from { width: 0; } to { width: 12ch; } } @keyframes blink-caret { 50% { border-color: transparent; } } </style> </head> <body> <div class="typing">Hello, CSS typing!</div> </body> </html>
Output
The text "Hello, CSS typing!" appears letter by letter from left to right with a blinking vertical line cursor at the end.
Common Pitfalls
- Not setting
white-space: nowrapcauses the text to wrap and breaks the typing effect. - Forgetting
overflow: hiddenshows the full text immediately. - Using
animation-timing-function: linearinstead ofsteps()makes the text appear to fade in instead of typing letter by letter. - Not matching the
steps(n)count to the number of characters causes the animation to jump incorrectly.
css
/* Wrong: linear timing causes smooth fade instead of typing */ .typing { animation: typing 4s linear forwards; } /* Right: steps timing for discrete letter reveal */ .typing { animation: typing 4s steps(20) forwards; }
Quick Reference
Remember these key points for typing animation:
- Use
@keyframesto animatewidthfrom 0 to full text width. - Set
white-space: nowrapandoverflow: hiddenon the text container. - Use
steps(n)in animation timing to reveal text letter by letter. - Add a blinking cursor with a border and a separate blinking animation.
Key Takeaways
Use CSS keyframes to animate the width of a text container for typing effect.
Apply white-space nowrap and overflow hidden to hide overflowing text.
Use steps() timing function to reveal text one character at a time.
Add a blinking border-right to simulate a cursor.
Match steps count to the number of characters for smooth animation.