等宽字体(monospaced font) 指字符宽度相同的电脑字体。
ch (character with) 表示数字 “0” 的宽度。
在等宽字体的前提下,一个英文字母的宽度为1ch。
假设我们有 26 个英文字符,只需要设定一个动画,让它的宽度变化从 0 - 100% 经历 26 帧即可,配合 overflow: hidden,steps 的每一帧即可展出一个字符。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
body {
background: black;
color: #fff;
}
h1 {
font: bold 200% Consolas, Monaco, monospace;
border-right: 0.1em solid;
width: 26ch;
margin: 2em 1em;
white-space: nowrap;
overflow: hidden;
animation: typing 6s steps(26, end), cursor-blink 0.6s step-end infinite alternate;
}
@keyframes typing {
from {
width: 0;
}
}
@keyframes cursor-blink {
50% {
border-color: transparent;
}
}
</style>
</head>
<body>
<h1>Just crawl inside your bed</h1>
</body>
</html>