0
0

【CSS】1つのHTML要素に複数のkeyframeアニメーションを適用させる

Posted at

はじめに

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です。

index.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つのアニメーションが動いている事が確認できました。

keyframe.gif

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0