今回はCSSを使用して上下左右いずれかに動くフェードインアニメーションの実装の仕方を説明していきます。
初心者の人でも使いやすく基本的に丸々コピペでOKな様にしますのでぜひ使ってみて下さい。
アニメーションの設定
CSSでアニメーションを作るには「animation」プロパティを使って下記の様にスタイルシートにアニメーション設定の記述を行います。
.animation1 {
// アニメーション設定
animation-name: animation1; //アニメーションの名前
animation-duration: 3s; //アニメーション時間
animation-timing-function: ease-out; //アニメーションさせるイージング
animation-delay: 1s; //アニメーション開始させる時間
animation-iteration-count: 1; //繰り返し回数
animation-direction: normal; //往復処理をするかどうか
animation-fill-mode: forwards; //アニメーション後のスタイルをどうするか
}
アニメーションを行う
次に「@keyframes」を定義する事で、定義されたアニメーション名を持つ「animation」の規則に沿って動作が行われます。
下記が、実際に記述したアニメーションです。
アニメーション1(フェードイン)
HTML/CSSの記述は以下の様。(コピペOK)
<p class="an1-fadein">アニメーション1(フェードイン)</p>
<style>
.an1-fadein {
background-color:#ff7f50;
font-size: 30px;
font-weight: bold;
animation-name: fadein;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
今回は分かりやすくするために「animation-iteration-count(繰り返し回数)」を「infinite(無限)」に設定しています。ここを「1」にすれば繰り返しは無くなります。
また「transform:」に値を付ければどの方向からフェードインするかを指定できます。以下からの記述は左右上下のフェードインの見本です。
下からフェードイン(コピペOK)
アニメーション2(フェードアップ)
<p class="an2-fadeup">アニメーション2(フェードアップ)</p>
<style>
.an2-fadeup {
background-color:#ff7f50;
font-size: 30px;
font-weight: bold;
animation-name: fadeup;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes fadeup {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
上からフェードイン(コピペOK)
アニメーション3(フェードダウン)
<p class="an3-fadedown">アニメーション3(フェードダウン)</p>
<style>
.an3-fadedown {
background-color:#ff7f50;
font-size: 30px;
font-weight: bold;
animation-name: fadedown;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes fadedown {
from {
opacity: 0;
transform: translateY(0);
}
to {
opacity: 1;
transform: translateY(20px);
}
}
</style>
横から(右から左)(コピペOK)
アニメーション4(フェードレフト)
<p class="an4-fadeleft">アニメーション4(フェードレフト)</p>
<style>
.an4-fadeleft {
background-color:#ff7f50;
font-size: 30px;
font-weight: bold;
animation-name: fadeleft;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes fadeleft {
from {
opacity: 0;
transform: translateX(150px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
</style>
横から(左から右)(コピペOK)
アニメーション5(フェードライト)
<p class="an5-faderight">アニメーション5(フェードライト)</p>
<style>
.an5-faderight {
background-color:#ff7f50;
font-size: 30px;
font-weight: bold;
animation-name: faderight;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes faderight {
from {
opacity: 0;
transform: translateX(0);
}
to {
opacity: 1;
transform: translateX(150px);
}
}
</style>
以上が「CSSで上下左右のフェードインアニメーションを実装する方法」でした。
アニメーションの技術は最近のWEB制作では必須かなと思うくらい当たり前の様に使われているので、まずは今回の様にCSSで簡単に実装できる方法から身につけていきましょう。