Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 4 of 9
Labels, Fieldset & Form Structure
Proper form structure is critical for accessibility. The <label> element connects text to its input - clicking the label focuses the input, and screen readers announce it. The <fieldset> and <legend> elements group related inputs (like 'Personal Information' or 'Payment Details'), providing visual and semantic structure.
Labels & Fieldsets
Every input MUST have a label. There are two ways to connect them:
1. Explicit label (recommended):
<label for="email">Email</label>
<input type="email" id="email" name="email">
The 'for' attribute matches the input's 'id'.
2. Implicit label (wrapping):
<label>Email <input type="email" name="email"></label>
The input is nested inside the label - no for/id needed.
Fieldset groups related inputs:
<fieldset>
<legend>Shipping Address</legend>
<label for="street">Street</label>
<input id="street" name="street">
<label for="city">City</label>
<input id="city" name="city">
</fieldset>
Screen readers announce: 'Shipping Address group' when entering the fieldset, giving blind users context about what the fields are for.
Rules:
• NEVER use placeholder as a replacement for labels - placeholders disappear when typing.
• Use fieldset for radio button groups and checkbox groups - the legend acts as the group label.
• The 'name' attribute is what gets sent to the server. The 'id' is for label connection. Both are needed.
fieldset and legend group related inputs and announce context to screen readers
Form Structure Example
<!DOCTYPE html>
<html>
<head>
<style>
fieldset { border:1px solid #ddd; border-radius:8px; padding:16px; margin:12px 0; }
legend { font-weight:bold; color:#229c6b; padding:0 8px; }
label { display:block; margin:8px 0 4px; font-weight:500; }
input, select { width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; box-sizing:border-box; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" required>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" required>
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label><input type="checkbox" name="newsletter"> Subscribe to newsletter</label>
<label><input type="checkbox" name="terms" required> I agree to terms</label>
</fieldset>
<button type="submit" style="padding:10px 24px;background:#229c6b;color:white;border:none;border-radius:6px;cursor:pointer">Submit</button>
</form>
</body>
</html>Quick Quiz: Form Structure
Finished this lesson?