π±BeginnerAttributes and Accessibility
ARIA and Accessibility
Improve screen reader support with ARIA roles, aria-label, and aria-hidden.
Overview
ARIA (Accessible Rich Internet Applications) is a set of HTML attributes that communicate semantic information to assistive technologies (screen readers) when native HTML semantics aren't enough.
The first rule of ARIA: don't use ARIA if a native HTML element or attribute provides the same semantics. <button>, <label>, and semantic elements do more than ARIA attributes.
Key ARIA attributes:
- role: defines the element's purpose (button, navigation, dialog)
- aria-label: provides an accessible name for the element
- aria-labelledby: references another element as the label
- aria-hidden="true": hides from screen readers (visual-only content)
- aria-expanded, aria-selected, aria-checked: state attributes
Key Points
- β’Rule 1: Use native HTML semantics first only add ARIA when HTML alone is insufficient
- β’role attribute overrides or adds semantic meaning for screen readers
- β’aria-label gives an accessible name to elements with no visible text
- β’aria-hidden="true" hides decorative elements from screen readers
- β’aria-expanded, aria-selected communicate interactive component states
- β’aria-live="polite" announces dynamic content updates to screen reader users
Examples
aria-label for icon-only buttons
<!-- Icon button with no visible text needs a label -->
<button aria-label="Close dialog">
<svg><!-- X icon --></svg>
</button>
<!-- Search button with icon + hidden text -->
<button>
<svg aria-hidden="true"><!-- Search icon --></svg>
<span class="sr-only">Search</span>
</button>sr-only is a CSS class that hides text visually but keeps it readable by screen readers.
ARIA roles and states for custom components
<!-- Custom toggle button -->
<div role="button" tabindex="0" aria-pressed="false" id="dark-mode">
Dark Mode
</div>
<!-- Accordion panel -->
<button aria-expanded="false" aria-controls="panel1">
Section 1
</button>
<div id="panel1" hidden>
<p>Panel content</p>
</div>aria-hidden for decorative content
<!-- Decorative icon screen readers skip it -->
<span aria-hidden="true">β
β
β
β
β</span>
<span class="sr-only">4 out of 5 stars</span>
<!-- Decorative image -->
<img src="divider.svg" alt="" aria-hidden="true">Common Mistakes
- Adding ARIA to elements that already have the same native semantics
- Using aria-hidden="true" on elements that contain keyboard-focusable children
- Forgetting that ARIA does not add behavior add keyboard handlers when using role="button" on a div
Note
The sr-only utility class pattern (position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0); white-space: nowrap;) makes text visible to screen readers but invisible on screen more robust than aria-label in some cases.
Exercises
Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.
Loading editorβ¦
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4