Sub topic 3
Labels: Naming Form Controls Clearly
Assume you know basic HTML structure and CSS selectors, including font-size, font-weight, and color. This chapter focuses on making text roles clear and keeping them accessible as the layout changes.
Label Form Controls by Their Role
A form label names a control. Use a <label> element instead of plain text, and connect it to the control with matching for and id values. This connection lets screen readers announce the field name and lets users click the label to focus the control.
<form>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email">
<button type="submit">Subscribe</button>
</form>Style labels as field names, not as headings. A modest weight and a small gap above the control usually provide enough emphasis.
label {
display: block;
margin-bottom: 0.25rem;
font-weight: 600;
}Contrast and Resizing Text
Text must remain readable against its background. Check normal text and secondary text such as captions separately. Do not rely on color alone to show a required or invalid field.
Use relative units such as rem for text. They respect the user’s base font-size better than fixed pixels.
Keep Styles Consistent with Custom Properties
CSS custom properties, also called variables, store shared values. A small type scale prevents each component from inventing its own size.
:root {
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.25rem;
--leading-body: 1.5;
}
body {
font-size: var(--text-base);
line-height: var(--leading-body);
}
label,
button {
font-size: var(--text-base);
}
figcaption {
font-size: var(--text-sm);
color: #595959;
}Adjust Text Across Screen Sizes
Responsive text changes with the viewport without losing user control. clamp() sets a minimum, flexible value, and maximum. Keep its bounds in rem.
h1 {
font-size: clamp(1.75rem, 1.2rem + 2vw, 3rem);
}Check Your Hierarchy
Inspect the page at normal size and at 200% zoom. Confirm that:
- Every control has a visible, associated label.
- Heading levels follow a logical order.
- Body text has comfortable line height and line length.
- Captions look secondary without becoming faint.
- Text remains readable when the viewport and base font-size change.
Exercise
What is wrong with <label>Email</label><input id="user-email">, and how do you fix it?
Show answer
The label has no for value, so it is not associated with the input. Use <label for="user-email">Email</label>.