【CSS】 アニメーション(animation)を少しズラして使い回す

この記事は約7分で読めます。
サーバー等の運営維持費を得るため記事内に自動表示される広告が含まれています

コーディングのイメージ

こんにちは、さち です。

CSS」の animation 機能を使うと、ウェブサイト上の「アニメーション」を比較的簡単に作ることができます。

ただ、animation って記述量が多いので、何個も書くのは嫌なんですよね……。(前より楽になってもさらに楽をしようとするのが人間)

そこで今回は、作成した animation を少しずつズラして使い回す再利用する)方法について書いていきます。

 

スポンサーリンク

サンプルソース

ソース

<div class="play"></div>
div {
  border-radius: 999px
}

.play {
  animation-name: moving;
  animation-duration: calc( 30s / 46 );
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes moving {
    0% { translate:   0px; background: deepskyblue; }
  100% { translate: 200px; background: red;         }
}

<div> 要素が、左右に往復し続けるアニメーションを作りました。

結果

表示結果

 

アニメーションを使い回す

先ほど作成したアニメーションを複数の <div> 要素に使いまわすようにして、animation-duration だけを変えてみます。

ソース

<div class="play" style="--cycles: 57;"></div>
<div class="play" style="--cycles: 56;"></div>
<div class="play" style="--cycles: 55;"></div>
<div class="play" style="--cycles: 54;"></div>
<div class="play" style="--cycles: 53;"></div>
<div class="play" style="--cycles: 52;"></div>
<div class="play" style="--cycles: 51;"></div>
<div class="play" style="--cycles: 50;"></div>
<div class="play" style="--cycles: 49;"></div>
<div class="play" style="--cycles: 48;"></div>
<div class="play" style="--cycles: 47;"></div>
<div class="play" style="--cycles: 46;"></div>

それぞれの <div> 要素に、CSS の変数 --cycles を設定して、それぞれに異なる値を持たせます。

div {
  border-radius: 999px
}

.play {
  animation-name: moving;
  animation-duration: calc( 30s / var(--cycles) );
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes moving {
    0% { translate:   0px; background: deepskyblue; }
  100% { translate: 200px; background: red;         }
}

CSS の変数 --cycles を使って animation-duration を変更します。

結果

表示結果

動きが同じでも animation-duration微妙に違う <div> 要素が複数でき、「ペンデュラムウェーブ」が完成しました。

例では animation-duration を変えましたが、animation-delay を変えて残像を作ったり、animation-direction を変えて対称的な動きをさせたり、色々できそうですね。

【おまけ】 attr() を使う方法

今回は使用しませんでしたが、CSS の attr() でも同じようなことができます。(HTML の「属性」に CSS 用の値を書いておき、attr() で読み込んで使う)

ただし、attr() の使用には注意が必要です。

attr() で文字列を読み込む機能は全ブラウザーが対応していますが、今回のような場面で必要になる「値の型(type)指定」など一部の新機能は、2026年6月現在「Chromium」系ブラウザーしか対応していません

「Firefox」は設定(about:config)を変えると対応できますが、そこまでするのは開発者だけなので、事実上使えません。

attr() の「機能」「対応」の状況については、下記リンク先ページを参照して下さい。

【機能】 → CSS: attr() - MDN
【対応】 → attr() - Can I use...

コメント

タイトルとURLをコピーしました