Labels & Fieldsets
Overview
Forms are notoriously difficult for disabled users to navigate. The <label> tag is the most critical accessibility component in a form. It programmatically links descriptive text to a specific input field. For able-bodied users, clicking a label automatically focuses its linked input (or checks the checkbox), vastly improving UI convenience. For complex forms, the <fieldset> and <legend> tags group related inputs together (like grouping 'Billing Address' fields separate from 'Shipping Address' fields).
Syntax
<!--
Method 1: The 'for' attribute links exactly to the input's 'id'.
This is the most robust and preferred method.
-->
<label for="username_input">Username:</label>
<input type="text" id="username_input" name="username">
<!--
Method 2: Wrapping the input entirely inside the label.
This creates an implicit link automatically.
-->
<label>
Password:
<input type="password" name="password">
</label>
<!-- Grouping related fields together semantically -->
<fieldset>
<legend>Select Notification Preferences</legend>
<label><input type="radio" name="notif" value="email"> Email</label>
<label><input type="radio" name="notif" value="sms"> SMS</label>
</fieldset>Common Pitfalls
- Linking a
forattribute to anameattribute instead of anid. The<label for="...">strictly looks for an HTML element with that exactid. Using thenamewill cause the link to silently fail. - Using
<div>and<span>to fake a label (e.g.,<span class="label">Name:</span> <input>). Screen readers will have absolutely no idea what the input is for, rendering the form unusable.
Interview Questions
<fieldset> benefit a group of radio buttons?By wrapping radio buttons in a <fieldset> and providing a <legend>, screen readers will announce the legend's context (e.g., 'Notification Preferences') before reading out the individual radio choices, ensuring the user knows what they are choosing.
Real-World Example
Using labels to create a massively larger click target for a tiny checkbox on mobile devices.
<!--
Trying to tap a tiny 16px checkbox on a phone is infuriating.
By linking it to a large label, tapping ANYWHERE on the text
will toggle the checkbox!
-->
<div style="padding: 20px; border: 1px solid #ccc;">
<label for="terms" style="cursor: pointer; display: block;">
<input type="checkbox" id="terms" name="terms">
I agree to the 50-page Terms and Conditions.
</label>
</div>Check Your Knowledge
Test your understanding of Labels & Fieldsets with these quick questions.