0Pricing
Tailwind CSS Academy · Lesson

Accessible Modals and Dropdowns

Add aria-modal, role dialog, focus trapping, and keyboard escape handling to ensure overlay components are fully accessible.

Why Accessibility Is Non-Negotiable

Modals and dropdowns are among the most commonly used interactive patterns in web UIs, and they are also among the most frequently inaccessible. Users who rely on screen readers, keyboard-only navigation, or switch controls cannot use poorly implemented overlays.

Making these components accessible is not optional — it is required by WCAG 2.1 (Web Content Accessibility Guidelines) and by laws like the ADA and the EU Web Accessibility Directive. Beyond compliance, accessible components are simply better UX for everyone.

Focus Management When Modal Opens

When a modal opens, keyboard focus must move into the modal so keyboard users do not have to tab all the way through the page to reach the modal's controls. Programmatically focus the first interactive element — usually the close button or the first form field.

Store a reference to the element that triggered the modal (const trigger = document.activeElement) before opening, so you can return focus to it when the modal closes. This preserves the user's navigation position in the page.

<script>
  let triggerEl = null;

  function openModal() {
    triggerEl = document.activeElement; // save current focus position
    const modal = document.getElementById('modal');
    modal.classList.remove('hidden');
    document.body.classList.add('overflow-hidden');

    // Move focus into the modal
    const firstFocusable = modal.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    if (firstFocusable) firstFocusable.focus();
  }

  function closeModal() {
    document.getElementById('modal').classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
    // Return focus to trigger
    if (triggerEl) triggerEl.focus();
  }
</script>

All lessons in this course

  1. Modal Dialog Structure
  2. Modal Open and Close Animation
  3. Dropdown Menu Component
  4. Accessible Modals and Dropdowns
← Back to Tailwind CSS Academy