preface

Sometimes we want a piece of text to appear character by character, mimicking typing. We tried to do this with CSS.

The first step

Text to be displayed:

<h1>hello world!</h1>
Copy the code

Add an animation and change the text width from 0 to maximum:

@keyframes typing {
  from {
    width: 0; }}h1 {
  width: 180px;
  overflow: hidden; // Hide the excess partwhite-space: nowrap; // Text does not wrapanimation: typing 8s;
}
Copy the code

We found that this effect did not meet our needs, and the problems were as follows:

  1. The animation is continuous, not verbatim.
  2. We currently specify a width180pxThis is dead text of different length, how should we calculate?

The second step

  • For the first problem, we can usesteps()Process.
  • For the second question, we can usechThis CSS unit carries relief.

Ch refers to the width of the “0” font, and in monospaced fonts, the width of the “0” font is the same as the width of all other fonts, so the problem can be expressed in units of CH.

The CSS after modification is

h1 {
 font: bold 200%Consolas, Monaco, monospace; // Equal-width fontwidth: 12ch; // Text widthoverflow: hidden;
 white-space: nowrap;
 border-right: 2px solid;
 animation: typing 8s steps(12); // Contains Spaces and symbols12Characters}Copy the code

The third step

We found that the cursor was missing. We used border-right to simulate the cursor:

@keyframes caret {from {border-color: transparent; } } h1 { font: bold 200% Consolas, Monaco, monospace; width: 12ch; overflow: hidden; white-space: nowrap; border-right: 2px solid; Animation: Typing 8S steps(12), caret 1s steps(2) infinite; / / animation}Copy the code

Complete CSS example

@keyframes typing {
  from {
    width: 0;
  }
}

@keyframes caret {
  from {
    border-color: transparent;
  }
}

h1 {
  font: bold 200% Consolas, Monaco, monospace;
  width: 12ch;
  overflow: hidden;
  white-space: nowrap;
  border-right: 2px solid;
  animation: typing 8s steps(12), 
             caret 1s steps(2) infinite;
}
Copy the code

reference

  • CSS Revealed