CSS3だけでタイピングアニメーション|stepsとkeyframesの使い方
CSS3だけでタイピングアニメーションを実装する方法を解説します。JavaScriptを使わずに、@keyframes、steps、border-rightを利用して文字が1文字ずつ表示される表現を作る手順をサンプルコード付きでわかりやすく紹介します。
環境
- OS windows10 64bit
- chrome 86.0.4240.198
タイピングアニメーション
animationの動きはwidth: 文字数emをsteps(n)で文字数分コマ送りをしています。カーソルはborder-rightの色を透明にするアニメーションを繰り返すことで表現しています。
/*アニメーションのcss*/
.typewriteranime{
animation: typewriter 3s steps(19) 1s 1 normal both,
blinkCursor 500ms steps(19) infinite normal;
}
@keyframes typewriter{
from{width: 0;}
to{width: 19em;}
}
@keyframes blinkCursor{
from{border-right-color: rgba(255,255,255,.75);}
to{border-right-color: transparent;}
} サンプルコード
以下は実際に、テキストをタイピングアニメーションで表示したサンプルコードとなります。
<section>
<style>
#samplecode{
padding: 3em 2em;
color: #37b507;
background-color: #ececec;
}
.typewritertext{
width: 19em;
margin: 0 auto;
border-right: 2px solid #37b507;
font-weight: bold;
text-align: center;
white-space: nowrap;
overflow: hidden;
}
/* Animation */
.typewriteranime{
animation: typewriter 3s steps(19) 1s 1 normal both,
blinkCursor 500ms steps(19) infinite normal;
}
@keyframes typewriter{
from{width: 0;}
to{width: 19em;}
}
@keyframes blinkCursor{
from{border-right-color: #37b507;}
to{border-right-color: transparent;}
}
</style>
<div id="samplecode">
<p class="typewritertext typewriteranime">CSS3だけでタイピングアニメーション!</p>
</div>
</section>ブラウザ上で表示した結果
(ページを再読み込みするとアニメーションが動きます。)
CSS3だけでタイピングアニメーション!
補足
CSSだけでタイピングアニメーションを作成する場合は、@keyframesとsteps()を組み合わせる方法がよく利用されます。
steps()を使うことで、文字がなめらかに広がるのではなく、1文字ずつ入力されているような動きを表現できます。
.typing {
width: 20ch;
overflow: hidden;
white-space: nowrap;
border-right: 2px solid;
animation: typing 3s steps(20), blink .6s step-end infinite alternate;
}
@keyframes typing {
from {
width: 0;
}
}
@keyframes blink {
50% {
border-color: transparent;
}
}文字数に合わせてwidthやsteps()の数値を調整すると、より自然なタイピング風アニメーションになります。
参考リンク
-
前の記事
rails6 接続先のIPを取得して表示する 2021.01.14
-
次の記事
javascript canvasで画像を繰り返して表示する 2021.01.14
コメントを書く