Easy Typewriter Animation with TailwindCSS v3 in React

JsKnox
1 min readDec 10, 2021

--

Keyboard typing effect with straight CSS and Tailwind. No one-off dependencies. No Javascript needed.

Try it out in the playground

1. Add some keyframes to React

<style>{`@keyframes typewriter{0%{max-width:0%} 50%{max-width:100%} 100%{max-width:100%}}`}</style>

In plain HTML, this would be written more like:

<style>
@keyframes typewriter{
0% {max-width:0%}
50% {max-width:100%}
100% {max-width:100%}
}
</style>

This example has three keyframes (half the time will be animating, the other half will stay unchanged so the viewer can read it)

max-width animation is best to avoid increasing the box beyond its container size

2. Add your Tailwind “arbitrary” class with []

Use square brackets for arbitrary class in Tailwind and tie it into the keyframe we named “typewriter”.

<span className={"[animation:8s_typewriter_infinite_steps(50,end)] max-w-0 overflow-x-hidden inline-flex"}>{`This text will be typed out`}</span>

You will see this is all standard CSS animation. It is like writing the following CSS:

animation-name:typewriter;
animation-duration: 8s;
animation-iteration-count: infinite;
animation-timing-function: steps(50, end);

steps(…) allows us to reveal the text in increments (like a typewriter) and without the typical smooth easing. We choose 50 steps because that approximates the number of characters for the given element width (you might want something different).

inline-flex is needed for max-width to work.

You could also add animation listeners to trigger subsequent animations or other more advanced effects.

--

--

No responses yet