This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Hi, I’m Banxia 👴, a sand sculptor who has just started writing. If you like my article, you can pay attention to ➕ like 👍 pay attention to the public number: Banxia words front end, learn more front-end knowledge!

preface

If you often read CSS articles, you will often see the typewriter effect on a single line of text.

The main implementation logic at the moment is

  1. The text appears gradually by setting the width of the text container from 0 to the total length of the text. But the total length of the text is harder to get. Most schemes calculate px* total word count or EM * total word count
  2. Ensure that the text appears individually by setting steps() to animate the text.

The implementation logic of this article is still the basic idea above, but it will be improved to make a universal single-line typewriter effect.

The container

.text { max-width: 0; white-space: nowrap; overflow: hidden; font-size: 16px; animation: typing 3s steps(var(--textlen)) ; } <div class="text" > I am typewriter effect of text </div>Copy the code

The initial width of the container is set to 0. I’m using max-width, or I can use width. Overflow guarantees that redundant text will not appear.

A typewriter animation is invoked. Steps uses –textlen. The –textlen here holds the length of the text.

animation

Set the width change to the total length of the text.

@keyframes typing { 100% { max-width: calc(var(--textlen) * 16px); }}Copy the code

Js fetch length

Here is style.setProperty, which directly changes the CSS variable value, so you don’t need to calculate max-width and steps() first.

const text = document.getElementById("text");
const content = text.innerHTML;
text.style.setProperty("--textlen", content.length);
Copy the code

Ch replace px

In CSS, ch is the size relative to the number 0. One ch is equal to a width of zero. In CSS, under Chinese, a character is 2CH. In English, a letter is 1ch.

So with this specificity, we don’t have to worry about the parent px. Only need to:

English:

max-width: calc(var(–textlen) * 16px); Max-width: calc(var(–textlen) * 2ch);

English:

max-width: calc(var(–textlen) * 16px); Max-width: calc(var(–textlen) * 1ch);

Please note: according to the difference of font-family Settings, 2CH still cannot display a complete Chinese character in Chinese.

For example, in the font-family: sans-serif; In this case, you can’t show it in its entirety. I’m still working on that.

In the case of font-family:monospace, it can be fully displayed

The effect

Afterword.

For pure CSS typewriter effect, need to count the length of the text, as well as the number of characters, more troublesome. The use of CSS variables plus JS, to avoid the tedious manual counting.