CSS3だけでタイピングアニメーション

CSS3だけでタイピングアニメーション

CSS3のanimation プロパティを使って、テキストがタイプライターのように一文字づつ表示されるアニメーションのサンプルコードを記述しています。

環境

  • 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だけでタイピングアニメーション!