A CSS-only typewriter effect works, but it tends to be sized for one specific string: you pick a monospace font, count characters, and hard-code timing values around that count. A JavaScript version can take any text you hand it — any number of words, any number of characters — and adjust itself accordingly. No code changes when you add a word.
Markup: three real elements
The construct is a container holding three elements: the actual text, an element that hides the text, and the cursor.
<div class="container">
<div class="text_hide"></div>
<div class="text">Typing Animation</div>
<div class="text_cursor"></div>
</div>
Pseudo-elements (::before / ::after) are viable in CSS but are the wrong tool here. They aren't part of the DOM, which makes them awkward to reach from JavaScript. Real elements keep the animation fully scriptable.
Everything sits on a monospace font. Equal horizontal space per character is what makes the later steps() timing predictable — once a character's width is known and shared, the math stays simple.
The masking element and the cursor
The .text_hide div is the load-bearing trick: an empty element stretched over the text, which blocks it from view. Animate the element's position and the text appears to emerge from underneath it.
Coverage requires it to match the text element exactly: same height, same width, placed on top. Its background-color must be identical to the background surrounding the text, so the mask is invisible.
.container {
position: relative;
}
.text {
font-family: 'Roboto Mono', monospace;
font-size: 2rem;
}
.text_hide {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: white;
}
The cursor follows the same sizing rules. Given its own class, .text_cursor, it sets background-color: transparent and instead draws a single border on its left edge to form the caret. Blinking comes later.
.text_cursor{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: transparent;
border-left: 3px solid black;
}
Splitting the string
All logic lives inside a function, typing_animation(), which takes the text and prepares the arrays used by the animations.
function typing_animation(){
// code here
}
typing_animation();
split("") returns an array with one substring per character — every character becomes its own element.
function typing_animation(){
let text_element = document.querySelector(".text");
let text_array = text_element.innerHTML.split("");
}
"Typing Animation" yields:
![(16) ["T", "y", "p", "i", "n", "g", " ", "A", "n", "i", "m", "a", "t", "i", "o", "n"]](https://css-tricks.com/wp-content/uploads/2021/07/s_8EA91DCFAB4CC63A2BECFD2BD0D915F37F564BADB0336D1C310FCB8E38E3C85F_1624639698011_array.jpg)
Calling split(" ") instead uses the single space as a separator, terminating each substring at every space and returning words.
function typing_animation(){
let text_element = document.querySelector(".text");
let text_array = text_element.innerHTML.split("");
let all_words = text_element.innerHTML.split(" ");
}
![(2") ["Typing", "Animation"]](https://css-tricks.com/wp-content/uploads/2021/07/s_8EA91DCFAB4CC63A2BECFD2BD0D915F37F564BADB0336D1C310FCB8E38E3C85F_1624640608689_words.jpg)
Character counts come next. Total length is the length of the array of characters. Per-word length uses map() over all_words to build a parallel word_len array: the same number of elements as all_words, one holding each word, the other holding that word's length.
function typing_animation() {
let text_element = document.querySelector(".text");
let text_array = text_element.innerHTML.split("");
let all_words = text_element.innerHTML.split(" ");
let text_len = text_array.length;
const word_len = all_words.map((word) => {
return word.length;
});
}

Animating with the Web Animations API
No CSS animations involved — this uses the Web Animations API, so keyframes and timing are JavaScript objects.
The cursor blinks infinitely. Three keyframe objects go in an array, and the offset: 0.7 on one of them means that once 70% of the animation's time has elapsed, opacity flips from 0 to 1.
document.querySelector(".text_cursor").animate([
{
opacity: 0
},
{
opacity: 0, offset: 0.7
},
{
opacity: 1
}
], cursor_timings);
Timing properties are then collected in a single options object, and the animation can be given a name.
let cursor_timings = {
duration: 700, // milliseconds (0.7 seconds)
iterations: Infinity, // number of times the animation will work
easing: 'cubic-bezier(0,.26,.44,.93)' // timing-function
}
let animation = document.querySelector(".text_cursor").animate([
// keyframes
], //properties);
The .text_hide element drives the reveal. Its easing is a steps() function, which moves the element in discrete segments instead of smoothly — that is what produces the typing rhythm. With a two-second duration, the function runs in 9 steps, one per character of "Animation," giving each step a duration of 2/9 = 0.22 seconds. The end argument, which happens to be the default, holds the element in its initial state until the first step's duration has finished. The fill property mirrors CSS's animation-fill-mode; forwards keeps the element at its last keyframe once the animation completes.
let timings = {
easing: `steps(${Number(word_len[0])}, end)`,
delay: 2000, // milliseconds
duration: 2000, // milliseconds
fill: 'forwards'
}
The keyframes move the mask from left: 0% to left: 100% — its width effectively shrinking from 100% to 0% as it travels. The same animation is applied to .text_cursor so the caret tracks the mask's left-to-right motion.
let reveal_animation_1 = document.querySelector(".text_hide").animate([
{ left: '0%' },
{ left: `${(100 / text_len) * (word_len[0])}%` }
], timings);
Why 100/text_len? For a nine-character word it resolves to 100/9, or 11.11%: one character expressed as a fraction of the whole word. Multiplying by the first word's length (here 9) gives 100%. Writing 100% directly would be equivalent here, but the formula is what makes multi-word cases work.
Handling several words
For "Typing Animation," the first word animates as above except that the steps() count grows by one — the space after the word has to be accounted for.
let timings = {
easing: `steps(${Number(word_len[0] + 1)}, end)`,
delay: 2000,
duration: 2000,
fill: 'forwards'
}
A single-word string has no trailing space to count. An if condition picks steps(${Number(word_len[0])}, end) for one word and steps(${Number(word_len[0] + 1)}, end) otherwise.
function typing_animation() {
let text_element = document.querySelector(".text");
let text_array = text_element.innerHTML.split("");
let all_words = text_element.innerHTML.split(" ");
let text_len = text_array.length;
const word_len = all_words.map((word) => {
return word.length;
})
let timings = {
easing: `steps(${Number(word_len[0])}, end)`,
delay: 2000,
duration: 2000,
fill: 'forwards'
}
let cursor_timings = {
duration: 700,
iterations: Infinity,
easing: 'cubic-bezier(0,.26,.44,.93)'
}
document.querySelector(".text_cursor").animate([
{
opacity: 0
},
{
opacity: 0, offset: 0.7
},
{
opacity: 1
}
], cursor_timings);
if (all_words.length == 1) {
timings.easing = `steps(${Number(word_len[0])}, end)`;
let reveal_animation_1 = document.querySelector(".text_hide").animate([
{ left: '0%' },
{ left: `${(100 / text_len) * (word_len[0])}%` }
], timings);
document.querySelector(".text_cursor").animate([
{ left: '0%' },
{ left: `${(100 / text_len) * (word_len[0])}%` }
], timings);
} else {
document.querySelector(".text_hide").animate([
{ left: '0%' },
{ left: `${(100 / text_len) * (word_len[0] + 1)}%` }
], timings);
document.querySelector(".text_cursor").animate([
{ left: '0%' },
{ left: `${(100 / text_len) * (word_len[0] + 1)}%` }
], timings);
}
}
typing_animation();
Remaining words are handled by a for loop. It starts at i = 1 because the first word has already been animated by the time the loop runs.
for(let i = 1; i < all_words.length; i++){
// code
}
for(let i = 1; i < all_words.length; i++){
const single_word_len = word_len[i];
}
Each subsequent word gets its own options object, and the fit-the-animation-to-the-text problem lives almost entirely in delay.
// the following code goes inside the for loop
let timings_2 = {
easing: `steps(${Number(single_word_len + 1)}, end)`,
delay: (2 * (i + 1) + (2 * i)) * (1000),
duration: 2000,
fill: 'forwards'
}
The first word's delay is two seconds; its duration is also two seconds, four seconds in total, but two seconds of that gap doesn't look natural, so the gap between words is set to two seconds as well. The second word therefore starts at 2 + 2 + 2, or six seconds, the third at 10 seconds, and so on. The pattern, in milliseconds:
(2 * (i + 1) + (2 * i)) * (1000)
| Length of the word | Duration taken by one character to animate |
| 6 | 2/6 = 0.33 seconds |
| 8 | 2/8 = 0.25 seconds |
| 9 | 2/9 = 0.22 seconds |
| 12 | 2/12 = 0.17 seconds |
Note the side effect: because the duration is fixed, a long word is revealed faster than a short one. Adjust duration and delay to taste.
The other edge case is the final word, which has no trailing space and must be excluded from the extra step in another if statement.
// the following code goes inside the for loop
if (i == (all_words.length - 1)) {
timings_2.easing = `steps(${Number(single_word_len)}, end)`;
let reveal_animation_2 = document.querySelector(".text_hide").animate([
{ left: `${left_instance}%` },
{ left: `${left_instance + ((100 / text_len) * (word_len[i]))}%` }
], timings_2);
document.querySelector(".text_cursor").animate([
{ left: `${left_instance}%` },
{ left: `${left_instance + ((100 / text_len) * (word_len[i]))}%` }
], timings_2);
} else {
document.querySelector(".text_hide").animate([
{ left: `${left_instance}%` },
{ left: `${left_instance + ((100 / text_len) * (word_len[i] + 1))}%` }
], timings_2);
document.querySelector(".text_cursor").animate([
{ left: `${left_instance}%` },
{ left: `${left_instance + ((100 / text_len) * (word_len[i] + 1))}%` }
], timings_2);
}
Keeping the words aligned
With two words, text_len is 16, so each character is 6.25% of the full width (100/text_len = 100/16). Scaled by the first word's length, 7, that gives 43.75 — the width of the first word is 43.75% of the entire string. The second word therefore has to begin exactly where the first ended.
0% is the first word's starting left value. Every later word must start at the previous word's final left value, tracked in left_instance:
if (i == 1) {
var left_instance = (100 / text_len) * (word_len[i - 1] + 1);
}
word_len[i - 1] + 1 is the previous word's length including its white space. The value is updated at the bottom of each loop iteration, so each word picks up where its predecessor finished.
left_instance = left_instance + ((100 / text_len) * (word_len[i] + 1));
From there, any number of words can go into the HTML and the animation adapts.
Looping forever
As written, the animation runs once. Making it infinite is a small change to the timing properties.
The result takes any words and any character counts without touching the code, animates across multiple words, and — with a small extra delay between each — reads as natural typing. CSS has multiple credible approaches to this effect and can be the better choice in a given situation. The JavaScript path is for what lies beyond CSS's reach: dynamic widths, dynamic step counts, and sequences whose length isn't known until runtime.



