はじめに
HTML要素にアニメーションを当てる際にCSSのkeyframe
を利用する事があると思います。
animation
プロパティにkeyframe
を指定したCSSを対象のHTML要素にあてることで、アニメーションを付与することができますが、1つのHTML要素に複数のkeyframe
アニメーションを付与したい時にはどうするのか疑問に思ったので調べてみました。
結論
シンプルで以外と簡単でした。
animation
プロパティにおいて「,」で区切ってkeframeを指定するだけでした。
以下2つのkeyframe
(changeColor 、rotate)を指定した例になります。
.hogeClass {
/* ~~ */
animation: changeColor 5s infinite alternate, rotate 5s infinite linear;
/* ~~ */
}
ソース
試しに上記の方法でanimation
プロパティに2つのkeyframe
を設定したUIを作成してみます。
まずはHTMLを準備しときます。
◆ HTML
以下は、div
タグでCSSを当てるための要素を1つ作成したHTMLです。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>keyframes html</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="keyframeElement"></div>
</body>
</html>
◆ CSS
以下のCSSでは色を変化させるkeyframe(changeColor)、要素を回転させるkeyframe(rotate)の2つを作成しています。
keyframeElement
クラスに対して、「,」区切りでanimation
プロパティにそれらのkeyframeを指定しています。
body {
padding: 0;
margin: 0;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.keyframeElement {
width: 50%;
height: 10vh;
background-color: red;
animation: changeColor 5s infinite alternate, rotate 5s infinite linear;
}
@keyframes changeColor {
0% {
background-color: red;
}
50% {
background-color: blue;
}
100% {
background-color: green;
}
}
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
実行例
ブラウザからUIの見た目を確認してみます。
keyframe
で指定した色の変化とUIの回転の2つのアニメーションが動いている事が確認できました。