【Scroll-driven Animations】cssのみで画面内に要素が入ってきた時にスクロールと連動するスクラブアニメーションの実装

[ ID : 12212 ]
【Scroll-driven Animations】cssのみで画面内に要素が入ってきた時にスクロールと連動するスクラブアニメーションの実装
実装目安
3分

概要

CSSだけで画面内に要素が入ってきた時にスクロールと連動するスクラブアニメーションを実装する方法を紹介

用途・要件

  • JSを使わずcssのみで画面内に要素が入ったことを判定してスクロールアニメーションを実装できる。
    2023年7月リリースなので対応ブラウザ要確認:https://caniuse.com/?search=animation-timeline

検証ブラウザ

  • Google Chrome(最新)
  • Microsoft Edge(最新)

実装



HTML

<div class="c-scloll">
    <div class="c-scloll__bg">↓スクロールしてください</div>
    <div class="c-scloll__target"></div>
    <div class="c-scloll__bg">↓スクロールしてください</div>
</div>

SCSS

.c-scloll {

&__bg {
height: 100vh; /* スクロールが発生するよう適当な高さを確保 */
width: 70vw;
margin: 0 auto;
background-image: repeating-linear-gradient(#eff3f6, #eff3f6 20px, #e1e9ef 20px, #e1e9ef 40px);
text-align: center;

}


&__target {
width: 300px;
height: 300px;
margin: 0 auto;
background: royalblue;

/* スクロールアニメーションの設定 */
animation: animation linear both; /* アニメーションを指定。イージングはlinear。animation-fill-modeはboth */
animation-timeline: view();
animation-range: contain 0% contain 50%; /* 開始: 要素がビューポートに完全に入った時、終了: ビューポートの真ん中 */
}
}

/* 円→正方形 に形状を変化させるキーフレーム */
@keyframes animation {
from {
clip-path: circle(0% at 50% 50%);
}
to {
clip-path: circle(70% at 50% 50%);
}
}

CSS

.c-scloll__bg {
  height: 100vh; /* スクロールが発生するよう適当な高さを確保 */
  width: 70vw;
  margin: 0 auto;
  background-image: repeating-linear-gradient(#eff3f6, #eff3f6 20px, #e1e9ef 20px, #e1e9ef 40px);
  text-align: center;

}


.c-scloll__target {
    width: 300px;
    height: 300px;
    margin: 0 auto;
    background: royalblue;

    /* スクロールアニメーションの設定 */
    animation: animation linear both; /* アニメーションを指定。イージングはlinear。animation-fill-modeはboth */
    animation-timeline: view();
    animation-range: contain 0% contain 50%; /* 開始: 要素がビューポートに完全に入った時、終了: ビューポートの真ん中 */
}

/* 円→正方形 に形状を変化させるキーフレーム */
@keyframes animation {
    from {
        clip-path: circle(0% at 50% 50%);
    }
    to {
        clip-path: circle(70% at 50% 50%);
    }
}

この記事をシェアする

全ての記事を見る

KONOCODEのメリット 無料会員登録