# モーダルダイアログのCSS実装

> HTML標準の<dialog>要素で作るモーダル。フォーカス管理とEscで閉じる挙動はブラウザ任せにでき、JSは開閉の数行だけです。

- カテゴリ: 表示・フィードバック
- URL: https://www.css-dictionary.com/recipes/modal-dialog/

## HTML

```html
<button type="button" id="open-modal" class="btn">モーダルを開く</button>

<dialog id="modal" class="modal" aria-labelledby="modal-title">
  <h2 id="modal-title">確認</h2>
  <p>この操作を実行しますか？</p>
  <div class="modal-actions">
    <button type="button" id="close-modal" class="btn btn-ghost">キャンセル</button>
    <button type="button" class="btn">実行する</button>
  </div>
</dialog>
```

## CSS

```css
.modal {
  border: 1px solid #e2d8c2;
  border-radius: 10px;
  padding: 24px;
  max-width: 320px;
  box-shadow: 0 12px 32px rgb(0 0 0 / 0.18);
}

.modal::backdrop {
  background: rgb(26 23 18 / 0.5);
}

.modal h2 {
  margin: 0 0 8px;
  font-size: 18px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
}

.btn {
  padding: 8px 16px;
  border: 1px solid #b0413e;
  border-radius: 6px;
  background: #b0413e;
  color: #fff;
  cursor: pointer;
}

.btn-ghost {
  background: transparent;
  border-color: #cbbfa5;
  color: #5c5445;
}
```

## JavaScript

```js
document.getElementById('open-modal').addEventListener('click', () => {
  document.getElementById('modal').showModal();
});
document.getElementById('close-modal').addEventListener('click', () => {
  document.getElementById('modal').close();
});
```

## 仕組みの解説

<dialog>要素の showModal() で開くと、最前面表示・背面の操作ブロック・Escキーで閉じる・フォーカスの閉じ込めをブラウザが標準で行います。背景の暗幕は ::backdrop 擬似要素でスタイルします。div とJSで自作するより短く、アクセシビリティの抜けも起きにくい実装です。

## 実装のポイント

開くボタンと閉じるボタンはtype="button"にします（form内でsubmit扱いになるのを防ぐ）。閉じるアニメーションを付けたい場合は@starting-styleとtransition-behaviorを検討してください。

## AIに依頼するときの文例

HTML標準の<dialog>要素を使ったモーダルダイアログを作ってください。showModal()で開き、::backdropで背景を暗くし、JSは開閉のイベントリスナーだけの最小構成にしてください。

## 使っているプロパティ

- [border](https://www.css-dictionary.com/property/border.md)
- [border-radius](https://www.css-dictionary.com/property/border-radius.md)
- [padding](https://www.css-dictionary.com/property/padding.md)
- [box-shadow](https://www.css-dictionary.com/property/box-shadow.md)
- [display](https://www.css-dictionary.com/property/display.md)
- [gap](https://www.css-dictionary.com/property/gap.md)

