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.
Modal Sizes
Modals come in three sizes: small, medium (default), and large. Click the buttons below to see each size:
Standard Example
Click the button below to open a standard modal dialog:
Usage
---
import ModalComponent from '../../components/Modal.astro';
import Button from '../../components/Button.astro';
---
<ModalComponent id="example-modal" title="Example Modal" size="md">
<p>Modal content goes here.</p>
<div slot="footer">
<Button>Cancel</Button>
<Button class="btn-primary">Confirm</Button>
</div>
</ModalComponent>
<Button onclick="window.openModal_example_modal()">Open Modal</Button> 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):
// 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 alertsmd- Medium (32rem / 512px max-width) - Default size, great for most use caseslg- 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.
Svelte & Vanilla: Svelte ¡ Vanilla: same HTML and BEM as in Usage above; add minimal JS for open/close and focus trap.