【Scroll-driven Animations】cssのみでページのスクロール進捗に連動するスクラブアニメーションの実装

[ ID : 12208 ]
【Scroll-driven Animations】cssのみでページのスクロール進捗に連動するスクラブアニメーションの実装
実装目安
3分

概要

CSSだけでスクロールアニメーションを実装する方法を紹介

用途・要件

  • JSを使わずcssのみでスクロールアニメーションを実装できる。
    2023年7月リリースなので対応ブラウザ要確認:https://caniuse.com/?search=animation-timeline

検証ブラウザ

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

実装



HTML

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

SCSS

.c-scloll {
height: 200vh; /* スクロールが発生するよう適当な高さを確保 */
width: 70vw;
margin: 0 auto;


&__bg {
height: 100%;
width: 100%;
background-image: repeating-linear-gradient(#eff3f6, #eff3f6 20px, #e1e9ef 20px, #e1e9ef 40px);
}

&__target {
/* スタイリング */
position: fixed;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background: royalblue;
transform-origin: bottom; /* 下部を変形の基準にしておく */
transform: translate(-50%, -50%);

/* スクロールアニメーションの設定 */
animation: animation linear; /* アニメーションを指定。イージングはlinear */
animation-timeline: scroll();
}
}
/* 垂直方向にスケールを変えるキーフレーム */
@keyframes animation {
from {
scale: 1 0;
}
to {
scale: 1 1;
}
}

/* 実装とは直接関係ないスタイル */
p {
text-align: center;
}

CSS

.c-scloll {
  height: 200vh; /* スクロールが発生するよう適当な高さを確保 */
  width: 70vw;
  margin: 0 auto;
}

.c-scloll__bg {
  height: 100%;
  width: 100%;
  background-image: repeating-linear-gradient(#eff3f6, #eff3f6 20px, #e1e9ef 20px, #e1e9ef 40px);
}

.c-scloll__target {
  /* スタイリング */
  position: fixed;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  background: royalblue;
  transform-origin: bottom; /* 下部を変形の基準にしておく */
  transform: translate(-50%, -50%);

  /* スクロールアニメーションの設定 */
  animation: animation linear; /* アニメーションを指定。イージングはlinear */
  animation-timeline: scroll();
}

/* 垂直方向にスケールを変えるキーフレーム */
@keyframes animation {
  from {
    scale: 1 0;
}
to {
    scale: 1 1;
}
}

/* 実装とは直接関係ないスタイル */
p {
    text-align: center;
}

この記事をシェアする

全ての記事を見る

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