スクロール位置を認識する要素

概要

「トップに戻る」リンクなどのフローティング ボタンは、必要なときにのみ表示することで、ユーザー エクスペリエンスを向上させることができます。このガイドでは、CSS container-scroll-state-queries を使用してこれらの要素を構築する方法について説明します。これにより、JavaScript のスクロール リスナーやオブザーバーに依存することなく、コンテナのスクロール位置に基づいて要素のスタイルを設定できます。

実装

1. スクロール コンテナを確立する

スクロール コンテナは、スクロール状態クエリ コンテナとして宣言する必要があります。

.scroller {
  overflow-y: auto;
  /* Establish this element as a scroll-state query container */
  container-type: scroll-state;
}

2. フローティング要素のスタイルを設定する

要素をコンテナ内に配置し、スタイルを設定します。デフォルトでは非表示にする必要があります。

.back-to-top {
  position: sticky;
  bottom: 20px;
  visibility: hidden;
  opacity: 0;
  translate: 0 20px;
  transition:
    visibility 0.3s,
    opacity 0.3s ease,
    translate 0.3s ease;
}

3. スクロール状態に対応する

scroll-state 関数で @container ルールを使用します。ユーザーが下にスクロールしたかどうかを確認するには、コンテナを上までスクロールできるかどうかを確認します。

/* When the container can be scrolled toward the top, it means the user has scrolled down */
@container scroll-state(scrollable: top) {
  .back-to-top {
    visibility: visible;
    opacity: 1;
    translate: 0 0;
  }
}

代替戦略

基本的なフォールバック

container-scroll-state-queries がサポートされていない場合、デフォルトの visibility: hidden により、フローティング要素は非表示のままになります。機能を確保するために、サポートされていないブラウザでも要素を常に表示するように選択できます。

/* Fallback for browsers that do not support the feature */
.back-to-top {
  visibility: visible; /* Always visible */
  opacity: 1;
}

/* Override for supported browsers to handle dynamic visibility */
@supports (container-type: scroll-state) {
  .back-to-top {
    visibility: hidden;
    opacity: 0;
  }
  
  @container scroll-state(scrollable: top) {
    .back-to-top {
      visibility: visible;
      opacity: 1;
      translate: 0 0;
    }
  }
}

高度な代替手段(Intersection Observer)

動的な表示が必要な場合は、IntersectionObserver を使用して、スクローラーの上部にあるセンチネル要素がビューから外れたときにクラスを切り替えます。

<!-- Sentinel element placed at the top of the scroller -->
<div class="scroll-sentinel"></div>
/* Marker styling to ensure it does not affect layout */
.scroll-sentinel {
  height: 0;
  width: 0;
  visibility: hidden;
}

.scrolled .back-to-top {
  visibility: visible;
  opacity: 1;
  translate: 0 0;
}
if (!CSS.supports('container-type', 'scroll-state')) {
  const sentinel = document.querySelector('.scroll-sentinel');
  const scroller = document.querySelector('.scroller');

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      // If the sentinel is NOT intersecting, it means the user has scrolled down
      if (!entry.isIntersecting) {
        scroller.classList.add('scrolled');
      } else {
        scroller.classList.remove('scrolled');
      }
    });
  }, { root: scroller });

  observer.observe(sentinel);
}