This is the 30th day of my participation in the August Challenge

Question origin

On TELEVISION, we’ve all seen a really cool video effect, usually when an important event is happening: a typing animation, accompanied by the rhythmic sound of a typewriter, effectively enhances the persuasability of the text.

For example, there is a VScode plug-in called “power model”, which has a very cool effect when typing code:

So, this cool visual effect, how to achieve on the web?

Today, we’ll try out a CSS implementation of typewriter effects.

Monospaced font

To animate typing, use a monospaced font. Monowidth fonts mean that each text or letter occupies the same width under the same font size. Common monowidth fonts include Menlo, Monaco, Courier New, monospace, etc.

How does typing animation work

Here we only illustrate how to achieve single-line typing animation! Here we only illustrate how to achieve single-line typing animation! Here we only illustrate how to achieve single-line typing animation!

Well, say it three times!

The idea is to use the Steps speed control function and Overflow: Hidden. Let’s take it one step at a time.

Unit of length CH

This unit was learned in CSS Secret, so let’s see what it means:

Ch is the width of the font 0.

As shown below, the width of 11ch:

How many characters can be put if the content is changed into Chinese?

It can be seen that the width of 11ch can accommodate five and a half Chinese characters, so it is not difficult to infer that the space occupied by one Chinese character is 2ch.

Let’s start with a simple animation:

Then we use Steps to switch to one text at a time:

Well, it worked!

The source code:

<! DOCTYPEhtml>
<head>
    <title>Typewriter animation</title>
</head>
<body>
    <h1>
        <! -- I love YOU! -->The country expresses clearly 99 96 is illegal!</h1>
</body>
<style>
    h1 {
        font-family: monospace;
        width:24ch;
        animation: typing 3s steps(12) infinite;
        border: 1px solid lightcoral;
        white-space: nowrap; /* Avoid text wrapping due to insufficient width */
        overflow: hidden;
    }
    @keyframes typing {
        from {
            width: 0; }}</style>

</html>
Copy the code