ナビゲーション ドロワー

概要

ナビゲーション ドロワーは、ビューポートの端からページ コンテンツの上にスライドして表示されるパネルで、背後のコンテンツはすべて暗くなります。トリガーボタンから開き、パネルを画面外にスワイプするか、暗くなった背景をタップするか、Esc キーを押すと閉じます。

このガイドでは、ドロワーを次のように実装します。

  • popover="manual" 要素が最上位レイヤにプロモートされ、パネルとその ::backdrop が、スタック コンテキストに関係なく、ページ上の他のすべての要素にオーバーレイされます。
  • 2 つの CSS スクロール スナップ ストップ(1 つは「開く」、もう 1 つは「閉じる」)を持つ水平スクロール コンテナ。スワイプ操作はブラウザによってネイティブに処理されます。これにより、JavaScript のポインタイベント コードを使用せずに、慣性、速度、中断のトラッキングを無料で実現できます。
  • 背景の不透明度をスクロール位置に関連付けるスクロール駆動型アニメーション。ユーザーがパネルをドラッグすると、暗転がスムーズにフェードイン、フェードアウトします。
  • パネル上の IntersectionObserver。ビューポートに完全に表示されたとき、またはビューポートから完全に消えたときを検出し、そのタイミングでフォーカス、aria-expanded、inert を更新します。

このアプローチは、JavaScript による transform アニメーションよりも好ましい方法です。スクロール メカニズムにより、ユーザーがパネルの位置を直接制御できるため(トゥイーンではなく、指で操作する)、ネイティブ モバイルアプリでユーザーが慣れている操作パターンに非常に近いものになります。

実装

1. マークアップ

ドロワーは、水平スクローラーを含む単一のポップオーバーで、表示可能な「シート」が含まれています。トリガーボタンはページ コンテンツ内にあります。

<!-- popover="manual" is REQUIRED. Do not use popover="auto" or "hint". -->
<div class="Drawer" id="drawer" popover="manual">
  <div class="Drawer-scroller">
    <nav class="Drawer-sheet" tabindex="-1">
      <!-- tabindex="-1" makes the sheet programmatically focusable so we
           can move focus into it when the drawer opens, without adding it
           to the natural tab order. -->
      <ul>
        <li><a href="/page-1">Page 1</a></li>
        <li><a href="/page-2">Page 2</a></li>
        <!-- ... -->
      </ul>
    </nav>
  </div>
</div>

<main>
  <header>
    <!-- aria-controls links the trigger to the drawer; aria-expanded
         reflects the current state for assistive tech. -->
    <button id="drawer-open"
            aria-label="Menu"
            aria-expanded="false"
            aria-controls="drawer">
      <!-- MANDATORY: Inline decorative SVGs MUST define aria-hidden="true" -->
      <svg aria-hidden="true" viewBox="0 0 24 24">...</svg>
    </button>
  </header>
  <!-- Page content. -->
</main>

2. スタイル

ポップオーバーをリセットしてビューポートを埋める

ポップオーバーはビューポート全体を覆う必要があります。これにより、::backdrop がページ全体を暗くし、スワイプ サーフェスが端から端まで広がります。デフォルトのユーザー エージェントのポップオーバー スタイル(中央揃え、自動サイズ、枠線付き)が邪魔になるため、リセットする必要があります。

.Drawer {
  /* min() caps the sheet width on large screens but on a phone leaves
     a 20% peek of page content visible, which is the affordance that
     tells the user they can tap outside to dismiss. */
  --drawer-width: min(20em, 80dvw);

  /* Custom property driven by the scroll-driven animation below.
     0 = drawer fully closed (transparent backdrop).
     1 = drawer fully open (visible backdrop). */
  --drawer-backdrop: 0;

  /* Reset UA popover style that would constrain the element. */
  width: auto;
  height: auto;
  background: transparent;
  border: 0;
  overflow: visible;
}

/* Style the popover's ::backdrop to achieve the overlay effect and
   provide visual affordances indicating that the rest of the page is inert */
.Drawer::backdrop {
  background: #000;
  /* Use calc() to limit the opacity range so the content beneath is visible */
  opacity: calc(var(--drawer-backdrop) / 2);
}

スクロール スナップを使用してスワイプ サーフェスを構築する

スクローラーは、ビューポートよりも幅の広い水平グリッドです。列 1 にはシート(幅 --drawer-width)が、列 2 にはビューポートの幅の空の疑似要素スペーサーが配置されています。2 つの列の間でスナップすることで、ドロワーが開閉します。

.Drawer-scroller {
  position: relative;
  display: grid;
  /* Sheet on the left, full-viewport spacer on the right. The user
     scrolls between the two snap stops to open and close. */
  grid-template-columns: var(--drawer-width) 100%;

  overflow-x: scroll;
  /* Stop the swipe from chaining into the page's vertical scroll
     when the user reaches either snap edge. */
  overscroll-behavior: none;
  scrollbar-width: none;
  /* `mandatory` guarantees the drawer always settles fully open or
     fully closed — never half-open after a partial swipe. */
  scroll-snap-type: x mandatory;
}

/* Enable smooth scrolling natively, but only if the user has not
   requested reduced motion. */
@media (prefers-reduced-motion: no-preference) {
  .Drawer-scroller {
    scroll-behavior: smooth;
  }
}

/* The empty spacer that creates the "closed" snap stop. */
.Drawer-scroller::after {
  content: '';
  scroll-snap-align: end;
  /* Open the popover already scrolled to this stop (drawer off-screen),
     so the JS only needs to scroll to the open position to
     animate it in. */
  scroll-initial-target: nearest;
}

.Drawer-sheet {
  display: grid;
  grid-template-rows: auto 1fr;
  /* Use `svh` (small viewport height) — not `vh` or `dvh` — so the
     sheet height does not jump when the iOS Safari address bar
     resizes mid-swipe. */
  height: 100svh;

  background: #333;
  color: #fff;
  overflow-y: auto;
  scroll-snap-align: start;
  scrollbar-width: none;
}

背景の不透明度をスクロール位置に関連付ける

スクロール駆動型アニメーションは、スクローラーの範囲全体で --drawer-backdrop を 1(開く)から 0(閉じる)にマッピングするため、背景はドラッグと完全に同期してフェードイン、フェードアウトします。

/* MANDATORY: Wrap this entire block in @supports. Browsers that don't
   support animation-timeline still parse the @keyframes and would
   apply the animation's `0%` value (--drawer-backdrop: 1) at all
   times, leaving the backdrop permanently opaque. The @supports gate
   ensures the animation is only registered where it actually works. */
@supports (animation-timeline: scroll()) {
  .Drawer {
    /* timeline-scope lets .Drawer reference a scroll-timeline that
       is defined on its descendant (the scroller). Without this, the
       timeline name is not visible to the .Drawer element. */
    timeline-scope: --drawer-fade;
    animation: fade-drawer-backdrop linear both;
    animation-timeline: --drawer-fade;
  }

  .Drawer-scroller {
    /* The horizontal scroll position of this element drives the
       timeline named `--drawer-fade`. */
    scroll-timeline: --drawer-fade x;
  }

  /* @property is REQUIRED. Without registering --drawer-backdrop with
     a `<number>` syntax, the browser treats it as a string and cannot
     interpolate it — the backdrop would jump from 0 to 1 with no
     fade. */
  @property --drawer-backdrop {
    syntax: '<number>';
    inherits: true;
    initial-value: 0;
  }

  @keyframes fade-drawer-backdrop {
    /* Scroll position 0 = drawer fully open = backdrop visible. */
    0% { --drawer-backdrop: 1 }
    /* Scroll position 100% = drawer fully closed = backdrop hidden. */
    100% { --drawer-backdrop: 0 }
  }
}

3. ドロワーを開閉する

開くには、ポップオーバーを最上位レイヤに昇格させ、シートをスクロールして表示するという 2 つのステップがあります。閉じる操作は 1 ステップです。スペーサーまでスクロールして戻ります。シートが完全に画面外に移動すると、オブザーバー(ステップ 4)がポップオーバーを非表示にします。

const drawer = document.getElementById('drawer');
const openBtn = document.getElementById('drawer-open');
const scroller = drawer.querySelector('.Drawer-scroller');
const sheet = drawer.querySelector('.Drawer-sheet');

function openDrawer() {
  // Show the popover first so the element is in the top layer before
  // we trigger any scrolling. `scroll-initial-target` (set on the
  // ::after spacer) places the initial scroll position at the closed
  // stop, so the drawer enters the top layer already off-screen.
  drawer.showPopover();

  // Scroll the sheet into view. The `behavior: 'auto'` option defers
  // to the CSS `scroll-behavior` property, which will be smooth unless
  // the user prefers reduced motion. Snap takes over at the end and
  // locks the drawer fully open.
  scroller.scrollTo({left: 0, behavior: 'auto'});
}

function closeDrawer() {
  // Scroll back to the spacer. Do NOT call hidePopover() here —
  // doing so would remove the element from the top layer mid-animation
  // and the close animation would not be visible. The
  // IntersectionObserver in step 4 hides the popover once the sheet
  // has actually left the viewport.
  scroller.scrollTo({left: scroller.offsetWidth, behavior: 'auto'});
}

4. 開閉状態を検出する

ドロワーの状態の信頼できる情報源として、スクロール位置ではなく、シートの IntersectionObserver を使用します。オブザーバーは、シートの移動方法(ユーザーのスワイプ、プログラムによるスクロール、スナップの収束)に関係なく起動するため、すべての閉じパスが同じコールバックに収束します。

function onDrawerOpened() {
  // Mark the rest of the page inert so keyboard and screen-reader
  // users cannot tab into content hidden behind the drawer.
  document.querySelector('main').inert = true;
  openBtn.setAttribute('aria-expanded', 'true');
  // Move focus into the drawer for keyboard users.
  sheet.focus();
}

function onDrawerClosed() {
  // Hide the popover only after the close animation completes,
  // so the slide-out is visible to the user.
  drawer.hidePopover();
  document.querySelector('main').inert = false;
  openBtn.setAttribute('aria-expanded', 'false');
}

// Treat "any pixel of the sheet visible inside the popover root" as
// "open enough to count as not closed". This threshold is intentionally
// tiny so the closed callback only fires once the sheet is truly gone.
const visibleThreshold = 1 / window.innerWidth;

const observer = new IntersectionObserver(
  (entries) => {
    // During programmatic scrolling the observer can deliver multiple
    // entries in one batch. Only the most recent describes the
    // current state; earlier entries are intermediate positions.
    const entry = entries.at(-1);
    if (entry.intersectionRatio < visibleThreshold) onDrawerClosed();
    if (entry.intersectionRatio === 1) onDrawerOpened();
  },
  // root: drawer makes the popover element the intersection root,
  // so the ratio reflects the sheet's visibility within the popover
  // (i.e. how much of it has been swiped on-screen).
  {root: drawer, threshold: [visibleThreshold, 1]},
);
observer.observe(sheet);

5. トリガー ハンドラと閉じるハンドラを接続する

// Open trigger.
openBtn.addEventListener('click', openDrawer);

// Light-dismiss: a tap on the dimmed area (anywhere inside the
// popover but outside the sheet) closes the drawer. We implement
// this manually because popover="manual" disables the browser's
// built-in light-dismiss (which would also fire mid-swipe — see step 1).
drawer.addEventListener('click', (event) => {
  if (!sheet.contains(event.target)) closeDrawer();
});

// Escape key. Listen on document because focus may be inside the
// drawer when the user presses Escape.
document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') closeDrawer();
});

代替戦略

Popover API、背景をフェードするスクロール駆動型アニメーション、scroll-initial-target は、シンプルなフォールバックを備えたプログレッシブ エンハンスメントであり、幅広いブラウザ サポートが必要な場合に簡単に実装できます。

背景フェードの代替(animation-timeline のサポートなし):

CSS.supports('animation-timeline: scroll()') で検出し、サポートされていない場合は scroll イベント リスナーから --drawer-backdrop を書き込みます。ステップ 2 の CSS @supports ブロックにより、サポートされていないブラウザではキーフレームが適用されないため、JavaScript の値のみが書き込まれます。

if (!CSS.supports('animation-timeline: scroll()')) {
  scroller.addEventListener('scroll', () => {
    // Same mapping as the @keyframes: 0 scroll = 1 (open),
    // sheet-width scroll = 0 (closed).
    const ratio = 1 - scroller.scrollLeft / sheet.offsetWidth;
    drawer.style.setProperty('--drawer-backdrop', ratio);
  });
}

初期スクロール位置のフォールバック(scroll-initial-target がサポートされていない場合):

CSS.supports('scroll-initial-target', 'nearest') で検出し、openDrawer() 内で、showPopover() の直後にスクローラーを閉じた位置にジャンプ スクロールします。これがないと、ドロワーはスライドイン アニメーションなしで、開いた状態で即座に表示されます。

async function openDrawer() {
  drawer.showPopover();

  if (!CSS.supports('scroll-initial-target', 'nearest')) {
    // Jump-scroll to the closed stop so the scroll below
    // animates the drawer in from off-screen.
    scroller.scrollTo({left: scroller.offsetWidth, behavior: 'instant'});
    // Wait two animation frames for the jump-scroll to commit.
    // A single rAF is not enough — the second `scrollTo` would
    // cancel the first before the browser has a chance to apply it.
    await new Promise((r) =>
      requestAnimationFrame(() => requestAnimationFrame(r))
    );
  }

  scroller.scrollTo({left: 0, behavior: 'auto'});
}

@property フォールバック(登録済みのカスタム プロパティなし):

@property が必要なのは、スクロール駆動型アニメーションがキーフレーム間で --drawer-backdrop を補間するためです。登録しない場合、プロパティは文字列として扱われ、フェードなしで 0 と 1 の間でジャンプします。上記のスクロール駆動型アニメーションのフォールバックが設定されている場合、その JavaScript はスクロール フレームごとに新しい数値文字列を --drawer-backdrop に書き込み、補間は行いません。そのため、スクロール駆動型アニメーションをサポートするすべてのブラウザは @property もサポートしているため、別の @property フォールバックは必要ありません。

Popover API のフォールバック(popover 属性のサポートなし):

このコンポーネントは popover="manual" を使用し、JavaScript から完全に閉じる動作を実装しているため、Popover API の定義動作(ライトディスミス、popovertarget 属性、最上位レイヤで管理される Escape 処理、フォーカス管理)に依存しません。実際に使用するポップオーバー機能は、最上位レイヤのプロモーション(showPopover() 経由)と ::backdrop 疑似要素のみです。

より幅広いブラウザのサポートが必要な場合は、機能検出で分岐せず、単にポップオーバーをまったく使用しないでください。popover="manual" 属性を削除し、最上位レイヤのプロモーションを position: fixed と高い z-index に置き換え、::backdrop を同じスタイル(同じ --drawer-backdrop カスタム プロパティを使用)の兄弟要素に置き換え、showPopover()/hidePopover() ではなくクラスから表示を切り替えます。コンポーネントの残りの部分(スクロール スナップ、スクロール駆動の背景アニメーション、IntersectionObserver、閉じハンドラ)は変更されません。