command / commandfor 属性で、JS なしのハンバーガーメニュー(dialog)を作る
<button commandfor="menu" command="show-modal"> で <dialog> を開閉し、動きは CSS の @starting-style などで付ける。クリック処理の JS が要らない。
どんな時に使う?
- スマホ表示のハンバーガーメニューやドロワーを、イベントリスナーを書かずに作りたいとき。
dialogを使うので、フォーカスの閉じ込め、Esc で閉じる、背面を操作不可にする、といったモーダルの基本動作をブラウザに任せたいとき。
コード
html
<button commandfor="menu" command="show-modal" aria-label="メニューを開く">☰</button>
<dialog id="menu" class="drawer">
<button commandfor="menu" command="close" aria-label="メニューを閉じる">×</button>
<nav>…</nav>
</dialog>css
.drawer {
margin: 0 0 0 auto; /* 右端に寄せる */
height: 100dvh;
max-height: none;
translate: 100% 0;
transition: translate .3s, display .3s allow-discrete, overlay .3s allow-discrete;
}
.drawer[open] {
translate: 0 0;
}
@starting-style {
.drawer[open] { translate: 100% 0; }
}
.drawer::backdrop {
background: rgb(0 0 0 / .4);
}command に入れる値は、モーダルで開く show-modal、閉じる close のほか、ポップオーバー用の toggle-popover などがある。commandfor には対象の id を書く。閉じるアニメーションは display と overlay を allow-discrete で遷移させると、消える前に動きが見える。
注意点
- Invoker Commands(
command/commandfor)は比較的新しい機能。2026-10 時点では主要ブラウザの最新版で使える目安だが、対象ユーザーの環境を Can I use で確認し、古い環境向けには JS のshowModal()で補う。 - 背面スクロールも止めたいときは :has(dialog:modal) でモーダル表示中の背面スクロールを止める と組み合わせる。
- 出典の投稿はデモ動画のみでコードは非公開。上のコードは手法を再構成したもの。