How to Create Typewriter Animation with CSS

css
Published on July 2, 2018

A typewriter effect can be created in CSS by using a monospace font for the text, and animating width CSS property of the text in a fixed number of steps (so that each character comes out in a single step).

Typewriter Effect Example

Twinkle, twinkle, little star.

Step 1 - Use a Monospace Font for Text

A monospace font contains letters and characters of equal width. This is different from conventional fonts in which characters are of different width.

To achieve a typewriter effect, it is important to use a monospace font. A monospace font, along with a valid animation-timing-function, will ensure that only a single character comes up in each step of the animation.

Some examples of monospace fonts are Courier, Consolas, Roboto Mono etc

Step 2 - Animate CSS Properties

  • To achieve the typewriter effect, the width property of text is being animated from 0% to 100%.
  • To achieve the the blinking cursor effect, the border-color property is being animated from a solid color to transparent.

Step 3 - Perform Animation in a Fixed Number of Steps

The main hero of this animation is the animation-timing-function property. To look like a realistic typing effect, we want the animation to push out a single character at a time. We don't want the animation as a smooth movement from one state to another, because then it won't look realistic. (You can try it yourself by editing the below codes).

Setting animation-timing-function as steps makes sure that the animation is performed in a series of steps. In short you can specify the number of "frames" in the animation.

In case of the text "Twinkle, twinkle, little star." - which contains 30 characters, the value becomes steps(30, end). The second parameter "end" specifies the movement to stay at the end till the duration of the step is over.

See How to Use steps() in CSS Animations for more.

HTML & CSS Code

<div class="typewriter">
    <div class="typewriter-text">Twinkle, twinkle, little star.</div>
</div>
.typewriter {
    font-family: Courier, monospace;
	display: inline-block;
}

.typewriter-text {
    display: inline-block;
  	overflow: hidden;
  	letter-spacing: 2px;
 	animation: typing 5s steps(30, end), blink .75s step-end infinite;
    white-space: nowrap;
    font-size: 30px;
    font-weight: 700;
    border-right: 4px solid orange;
    box-sizing: border-box;
}

@keyframes typing {
    from { 
        width: 0% 
    }
    to { 
        width: 100% 
    }
}

@keyframes blink {
    from, to { 
        border-color: transparent 
    }
    50% { 
        border-color: orange; 
    }
}

Related Resources

In this Tutorial
    Comments
    Loading Comments