Modal & Dialog Components

Production-ready modal implementations with pure CSS and modern HTML5

1. Basic Modal (Checkbox Hack)

Pure CSS modal using the checkbox hack - no JavaScript required!

How it works: Uses a hidden checkbox. When checked, the modal overlay becomes visible using the :checked pseudo-class. Clicking the backdrop or close button unchecks the checkbox.

2. Modal Sizes

3. Animation Variants

Different entry/exit animations for visual variety

4. Confirmation Dialogs

Styled confirmation modals for important actions

5. Form Modal

Modal containing a form for user input

6. Modern <dialog> Element

Using the native HTML5 <dialog> element with enhanced styling

Browser Support: The <dialog> element is well-supported in modern browsers (Chrome 37+, Firefox 98+, Safari 15.4+). Use a polyfill for older browsers.

7. Image Lightbox Modal

Click any placeholder to open in a lightbox modal

8. Scroll Lock (JavaScript Enhancement)

Pure CSS Limitation: The checkbox hack method doesn't prevent body scrolling when a modal is open.

JavaScript Solution:

// Add when modal opens document.body.style.overflow = 'hidden'; // Remove when modal closes document.body.style.overflow = '';

Or use the native <dialog> element which handles this automatically!

9. Accessibility Considerations

Important Accessibility Features:
  • Focus Management: When opening a modal, focus should move to the first focusable element
  • Focus Trap: Tab navigation should cycle within the modal (requires JavaScript)
  • ESC Key: Should close the modal (native with <dialog>)
  • ARIA Attributes: Use role="dialog", aria-modal="true", aria-labelledby
  • Screen Readers: Announce modal opening/closing
  • Return Focus: When closing, return focus to the trigger element
Note: The checkbox hack is great for simple demos, but for production use with full accessibility, consider using the native <dialog> element or a JavaScript-enhanced solution with proper focus management.

10. Implementation Tips

CSS-Only Approach (Checkbox Hack)

Pros:
  • No JavaScript required
  • Works without JS enabled
  • Simple implementation
Cons:
  • Limited accessibility
  • No focus management
  • No scroll lock
  • Multiple modals can be open simultaneously

HTML5 Dialog Element

Pros:
  • Built-in accessibility
  • Native focus management
  • ESC key support
  • Proper modal behavior
Cons:
  • Requires minimal JavaScript for show/hide
  • May need polyfill for older browsers

Recommended: Hybrid Approach

Use the <dialog> element styled with CSS for the best of both worlds:

  • Native accessibility features
  • Custom styling with CSS
  • Minimal JavaScript (just showModal() and close())
  • Progressive enhancement