スタッガー アニメーションは、複数の順序付けられた要素を、すべて一度にアニメーション化するのではなく、それぞれにわずかな遅延を加えて順番にアニメーション化する、興味深い効果を提供します。この手法は、リスト、ギャラリー、ナビゲーション メニューでよく使用され、ユーザーの視線を誘導し、インタラクションに洗練されたリズミカルな感覚を加えます。
sibling-index() を使用してアニメーションをずらす
animation-delay プロパティで sibling-index() プロパティを使用して、各要素のアニメーションが親要素内の位置に比例した数だけオフセットされるようにします。sibling-index() 関数は整数を返すため、時間単位を乗算して時間に変換する必要があります。
#stagger-list > .item {
--stagger-time: 0.1s;
/* Define the animation first */
animation: fade-in 0.4s;
/* Set the `animation-delay` to a time multiplied by the `sibling-index()` */
animation-delay: calc(sibling-index() * var(--stagger-time))
}
必須: 動きを抑えたいユーザーに対してアニメーションを無効にすることで、ユーザー設定を尊重します。
@media (prefers-reduced-motion: reduce){
/* Disable animation for users who prefer reduced motion. */
#stagger-list > .item {
animation: none;
}
}
代替戦略
sibling-index() のサポートをテストするには、@supports (animation-delay: calc(sibling-index() * 0.1s)){} を指定した CSS または !CSS.supports('animation-delay: calc(sibling-index() * 0.1s)') を指定した JavaScript を使用します。
古いブラウザでスタッガー アニメーションをサポートするには、JavaScript を使用して、各兄弟要素に --sibling-index カスタム プロパティを追加します。必須: 不要な JavaScript の実行を避けるため、これを CSS.supports('animation-delay: calc(sibling-index() * 0.1s)') テストでラップします。
if(!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')){
const staggerList = document.getElementById('stagger-list');
[...staggerList.children].forEach((el, index)=>el.style.setProperty('--sibling-index', index + 1));
}
--sibling-index カスタム プロパティを使用する animation-delay 宣言を追加します。sibling-index() 関数を使用する animation-delay 宣言の前に指定する必要があります。これを @supports でラップする必要はありません。古いブラウザは 2 番目の宣言を解析せず、最初の宣言を使用します。
#stagger-list > .item {
animation-delay: calc(var(--sibling-index) * var(--stagger-time));
animation-delay: calc(sibling-index() * var(--stagger-time));
}