Modal Component — Astro

Accessible modal/dialog component with focus trapping, keyboard navigation, and backdrop overlay

Modal Component

An accessible modal/dialog component with focus trapping, keyboard navigation, and backdrop overlay.

Add this component

The command below includes <strong>Modal</strong>—run it in your project directory to install this component (and the CSS if needed). No prompts.

Choose your package manager — click a tab to select, then copy the command.

npm pnpm yarn bun

Modal Sizes

Modals come in three sizes: small, medium (default), and large. Click the buttons below to see each size:

Live Examples

Standard Example

Live Example

Click the button below to open a standard modal dialog:

Usage

Usage

Full example for each framework (Astro, Vanilla, Svelte, Vue, React). Switch framework via View as or by clicking a Usage tab—both stay in sync.

Astro Vanilla Svelte Vue React

Props

  • id (string, optional) - Unique ID for the modal (auto-generated if not provided)
  • title (string, optional) - Modal title (default: "Modal")
  • size ('sm' | 'md' | 'lg', optional) - Modal size (default: "md")
  • open (boolean, optional) - Whether modal is open by default (default: false)
  • closeOnOverlayClick (boolean, optional) - Close when clicking overlay (default: true)
  • closeOnEscape (boolean, optional) - Close on Escape key (default: true)
  • class (string, optional) - Additional CSS classes

Slots

  • Default slot - Main modal content (goes in modal__body)
  • footer - Footer content with action buttons

Programmatic Control

Each modal exposes global functions based on its ID (hyphens converted to underscores):

javascript javascript
// Open modal (ID: example-modal becomes example_modal)
window.openModal_example_modal();

// Close modal
window.closeModal_example_modal();

Features

  • Full keyboard accessibility (Tab, Shift+Tab, Escape)
  • Focus trapping - focus stays within modal when open
  • ARIA attributes for screen readers
  • Backdrop overlay with blur effect
  • Responsive design (mobile-friendly)
  • Theme-aware styling using semantic variables
  • Respects prefers-reduced-motion

Size Variants

Control the modal width using the size prop:

  • sm - Small (24rem / 384px max-width) - Best for confirmation dialogs and simple alerts
  • md - Medium (32rem / 512px max-width) - Default size, great for most use cases
  • lg - Large (48rem / 768px max-width) - Ideal for complex forms and detailed content

Note: On mobile devices (≤640px), all modals automatically use 95vw width for better mobile experience.

Other frameworks: Vanilla · Svelte · Vue · React