Form Labels (Accessibility)
Overview
Have you ever tried clicking the tiny little square of a checkbox on your phone, but your finger missed it? It's incredibly annoying.
If the developer used `<label>` tags correctly, you could just tap the text NEXT to the checkbox, and the checkbox would magically activate! Labels connect descriptive text to an input field, which drastically improves user experience (UX) and is absolutely mandatory for blind users using screen readers.
Syntax
To connect a label to an input, the `for` attribute on the label MUST be exactly identical to the `id` attribute on the input. This creates a permanent, unbreakable link between the two.
<!-- ❌ WRONG: No connection. Clicking 'I Agree' does nothing. -->
<p>I Agree</p> <input type="checkbox" />
<!-- ✅ CORRECT: Clicking the text toggles the checkbox! -->
<label for="terms">I Agree to Terms</label>
<input type="checkbox" id="terms" name="terms" />You can also put the input DIRECTLY INSIDE the label tag. This automatically links them without needing `for` and `id`. However, Explicit Binding (above) is generally preferred for complex layouts.
<!-- Wrapping the input inside the label -->
<label>
Subscribe to newsletter
<input type="checkbox" name="newsletter" />
</label>Common Pitfalls
- A common beginner mistake is matching the label's 'for' attribute to the input's 'name' attribute. This is WRONG. It must match the input's 'id' attribute.
- Placeholder text (like placeholder='Enter Email') is NOT a replacement for a label. Once the user starts typing, the placeholder vanishes. Blind users won't know what they are typing into.
Real-World Example
A radio button group where you can click the large text labels instead of the tiny dots:
<fieldset>
<legend>Select Shipping Method</legend>
<div>
<input type="radio" id="standard" name="shipping" value="std" />
<label for="standard">Standard Shipping (3-5 days)</label>
</div>
<div>
<input type="radio" id="express" name="shipping" value="exp" />
<label for="express">Express Delivery (Next Day)</label>
</div>
</fieldset>