# タイプライターのCSSアニメーション実装

> 文字が1文字ずつ打たれていくタイプライター演出。steps()イージングとwidthアニメーション、点滅キャレットの組み合わせです。

- カテゴリ: テキスト
- URL: https://www.css-dictionary.com/animations/typewriter/

## HTML

```html
<p class="type">Typing with pure CSS!</p>
```

## CSS

```css
.type {
  font-family: 'Courier New', monospace;
  font-size: 18px;
  width: 21ch;
  white-space: nowrap;
  overflow: hidden;
  border-right: 3px solid #c2452f;
  animation:
    typing 2.4s steps(21) forwards,
    blink 0.7s step-end infinite;
}

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

@keyframes blink {
  50% { border-color: transparent; }
}

@media (prefers-reduced-motion: reduce) {
  .type {
    animation: blink 0.7s step-end infinite;
    width: 21ch;
  }
}
```

## 仕組みの解説

幅を0から21ch（=21文字分）へ、steps(21)で21段階に区切って広げることで「1文字ずつ現れる」動きになります。滑らかに広げるのではなく階段状に進むのがsteps()の役割です。右ボーダーをキャレットに見立て、別のアニメーションで点滅させています。ch単位は半角文字の幅基準なので、文字数とステップ数を一致させるのがコツです。

## 実装のポイント

日本語（全角）はchと幅が合わないため、この手法は等幅フォントの英数字向けです。日本語ではclip-pathを使う方法もあります。

## 使っているプロパティ

- [animation](https://www.css-dictionary.com/property/animation.md)
- [keyframes](https://www.css-dictionary.com/property/keyframes.md)
- [white-space](https://www.css-dictionary.com/property/white-space.md)
- [overflow](https://www.css-dictionary.com/property/overflow.md)
- [width](https://www.css-dictionary.com/property/width.md)

