Barrierefreie Modals und Dropdowns
Fügen Sie aria-modal, role dialog, Fokusfalle und die Verarbeitung der Escape-Taste hinzu, damit Overlay-Komponenten vollständig zugänglich sind.
Barrierefreie Modals und Dropdowns ist eine kostenlose Tailwind CSS Academy-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Tailwind CSS Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Tailwind CSS Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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>Focus Trapping Inside the Modal
While the modal is open, Tab and Shift+Tab must cycle only through the modal's interactive elements and not escape to the page behind it. This is called a focus trap.
Implement it by finding all focusable elements within the modal, detecting when the last one is focused and Tab is pressed (wrapping to the first), and detecting when the first is focused and Shift+Tab is pressed (wrapping to the last).
<script>
function trapFocus(modalEl) {
const focusable = modalEl.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const firstEl = focusable[0];
const lastEl = focusable[focusable.length - 1];
modalEl.addEventListener('keydown', (e) => {
if (e.key !== 'Tab') return;
if (e.shiftKey) {
// Shift+Tab on first element -> wrap to last
if (document.activeElement === firstEl) {
e.preventDefault();
lastEl.focus();
}
} else {
// Tab on last element -> wrap to first
if (document.activeElement === lastEl) {
e.preventDefault();
firstEl.focus();
}
}
});
}
</script>ARIA for Modal Dialogs
Modals require specific ARIA attributes for screen readers to understand the dialog context:
role='dialog'— identifies the element as a dialogaria-modal='true'— tells assistive technology that content behind the dialog is inertaria-labelledby— points to the dialog's visible title elementaria-describedby— optionally points to a description paragraph
Without these, a screen reader user opening a modal may not know they are in a dialog at all.
<div
id="modal"
role="dialog"
aria-modal="true"
aria-labelledby="modal-heading"
aria-describedby="modal-desc"
class="fixed inset-0 flex items-center justify-center z-50 p-4 hidden">
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
<h2 id="modal-heading" class="text-lg font-semibold text-gray-900">Confirm Action</h2>
<p id="modal-desc" class="mt-2 text-sm text-gray-600">
This action will permanently delete your account.
</p>
<div class="mt-5 flex justify-end gap-3">
<button onclick="closeModal()" class="px-4 py-2 text-sm font-semibold border border-gray-300 rounded-lg">Cancel</button>
<button class="px-4 py-2 text-sm font-semibold text-white bg-red-600 rounded-lg">Delete</button>
</div>
</div>
</div>Making Background Content Inert
When a modal is open, all page content behind the backdrop should be made inert — not focusable and not interactable by screen readers. The HTML inert attribute achieves this natively, and it is now supported in all modern browsers.
Apply inert to the main content area (not the modal or backdrop) when the modal opens, and remove it when the modal closes. This provides a native alternative to complex aria-hidden attribute management.
<script>
const mainContent = document.getElementById('main-content');
function openModal() {
// Make everything behind the modal inert
mainContent.setAttribute('inert', '');
mainContent.setAttribute('aria-hidden', 'true');
document.getElementById('modal').classList.remove('hidden');
document.body.classList.add('overflow-hidden');
}
function closeModal() {
// Restore background content
mainContent.removeAttribute('inert');
mainContent.removeAttribute('aria-hidden');
document.getElementById('modal').classList.add('hidden');
document.body.classList.remove('overflow-hidden');
}
</script>Dropdown ARIA Roles
Accessible dropdown menus require ARIA attributes on both the trigger and the panel. The trigger button gets aria-haspopup='true' (or aria-haspopup='menu') and aria-expanded='false'. When opened, update aria-expanded to 'true'.
The dropdown panel gets role='menu', and each item inside it gets role='menuitem'. This full role set allows screen readers to announce the dropdown as a menu and navigate items with arrow keys.
<div class="relative inline-block">
<!-- Trigger with ARIA -->
<button
id="dd-btn"
aria-haspopup="menu"
aria-expanded="false"
aria-controls="dd-menu"
onclick="toggleDropdown()"
class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium
text-gray-700 bg-white border border-gray-300 rounded-lg
hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
Account
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
</svg>
</button>
<!-- Panel with role=menu -->
<div
id="dd-menu"
role="menu"
aria-labelledby="dd-btn"
class="hidden absolute top-full left-0 mt-1 z-50 w-56 bg-white border border-gray-200 rounded-xl shadow-lg py-1">
<a href="/profile" role="menuitem" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Profile</a>
<a href="/settings" role="menuitem" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Settings</a>
</div>
</div>Arrow Key Navigation in Dropdowns
WCAG requires that dropdown menu items be navigable with arrow keys: Down Arrow moves to the next item, Up Arrow moves to the previous, Home moves to the first, End moves to the last. This mirrors native OS menu behavior that keyboard users expect.
Implement this by adding a keydown listener on the menu panel that moves focus between role='menuitem' elements. Items should receive tabindex='-1' so they are programmatically focusable but not part of the Tab order.
<script>
document.getElementById('dd-menu').addEventListener('keydown', (e) => {
const items = [...document.querySelectorAll('[role=menuitem]')];
const idx = items.indexOf(document.activeElement);
if (e.key === 'ArrowDown') {
e.preventDefault();
items[(idx + 1) % items.length].focus();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
items[(idx - 1 + items.length) % items.length].focus();
} else if (e.key === 'Home') {
e.preventDefault();
items[0].focus();
} else if (e.key === 'End') {
e.preventDefault();
items[items.length - 1].focus();
} else if (e.key === 'Escape') {
closeDropdown();
document.getElementById('dd-btn').focus();
}
});
</script>Visible Focus Styles on All Interactive Elements
Every button, link, and interactive element inside a modal or dropdown must have a clearly visible focus indicator. Tailwind's focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-1 provides this for keyboard users without showing a ring on mouse clicks.
Remove any outline-none classes on interactive elements unless you are providing a custom focus style in its place. Invisible focus is a WCAG failure.
<!-- Close button in a modal -->
<button
onclick="closeModal()"
aria-label="Close dialog"
class="p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg
focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500
focus-visible:ring-offset-1 transition-colors">
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>Screen Reader Only Text With sr-only
Sometimes a button's visible icon is self-explanatory visually, but a screen reader needs text to announce it. Tailwind's sr-only utility visually hides text while keeping it accessible to screen readers.
Use sr-only for icon-button labels when you do not want to use aria-label, or when you want the text to be part of the DOM (useful for some screen reader behaviors). The class applies position: absolute; width: 1px; height: 1px; overflow: hidden — making it invisible but present.
<!-- Icon button with sr-only label -->
<button
class="p-2 text-gray-500 hover:bg-gray-100 rounded-lg
focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500">
<svg class="w-5 h-5" aria-hidden="true" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
</svg>
<span class="sr-only">Close modal</span>
</button>Color Contrast in Overlays
Text inside modals and dropdown menus must meet WCAG AA contrast ratios: at least 4.5:1 for normal text and 3:1 for large text. Dark text on white backgrounds easily meets this, but subtle grays on white can fail.
The color text-gray-400 on a white background (#9ca3af on #fff) has a contrast ratio of approximately 2.5:1 — failing WCAG AA. Always use at least text-gray-500 (#6b7280, ~4.6:1) for body text in modals and text-gray-900 for primary text.
<!-- Failing contrast -->
<p class="text-gray-400">Helper text (fails WCAG AA)</p>
<!-- Passing contrast -->
<p class="text-gray-500">Helper text (passes WCAG AA ~4.6:1)</p>
<p class="text-gray-600">Body text (strong contrast ~5.9:1)</p>
<h2 class="text-gray-900">Heading (maximum contrast ~21:1)</h2>Live Region Announcements
When dynamic content appears inside a modal or dropdown (like a loading spinner transitioning to results), a live region ensures screen readers announce the change without the user having to navigate to it. Add aria-live='polite' to a container element that will receive updates.
aria-live='polite' queues the announcement for when the user is idle. Use aria-live='assertive' only for critical errors that need immediate interruption. Overusing assertive announcements is disruptive.
<div class="p-6">
<!-- Loading state -->
<div id="modal-status" aria-live="polite" aria-atomic="true" class="text-center">
<p class="text-sm text-gray-600">Loading results...</p>
</div>
</div>
<script>
// After data loads, update the region
// Screen reader will announce the change
function showResults(data) {
document.getElementById('modal-status').innerHTML =
'<p class="text-sm text-green-600">Found ' + data.length + ' results.</p>';
}
</script>Quick Check
Test your understanding of Tailwind CSS Mastery concepts from this lesson.
Lesson Recap
In this lesson you learned: modal accessibility requires focus management (trap focus inside, return focus on close), role='dialog' aria-modal='true', and the HTML inert attribute to lock background content; dropdown ARIA uses role='menu' on the panel, role='menuitem' on items, aria-haspopup='menu' and aria-expanded on the trigger; and Tailwind's sr-only provides screen-reader-only labels for icon-only controls. Next up we explore how the JIT engine works.
Häufig gestellte Fragen
Ist die Lektion „Barrierefreie Modals und Dropdowns“ kostenlos?
Ja — der vollständige Text von „Barrierefreie Modals und Dropdowns“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Tailwind CSS Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Tailwind CSS Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Barrierefreie Modals und Dropdowns“?
Fügen Sie aria-modal, role dialog, Fokusfalle und die Verarbeitung der Escape-Taste hinzu, damit Overlay-Komponenten vollständig zugänglich sind. Du übst Tailwind CSS Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Tailwind CSS Academy zu starten?
Keine Vorkenntnisse erforderlich. Tailwind CSS Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Barrierefreie Modals und Dropdowns“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Tailwind CSS Academy-Lektion Code schreiben und ausführen?
Ja. Jede Tailwind CSS Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Struktur eines Modaldialogs
- Animation zum Öffnen und Schließen eines Modals
- Dropdown-Menü-Komponente
- Barrierefreie Modals und Dropdowns